更改后的Angular JS更新输入字段

map*_*ap7 44 angularjs

我正在尝试在Angular中构建一个简单的计算器,我可以根据需要覆盖总计.我有这个部分工作,但当我然后返回输入一个或两个字段中的数字时,总数未在该字段中更新.

这是我的jsfiddle http://jsfiddle.net/YUza7/2/

表格

<div ng-app>
  <h2>Calculate</h2>

  <div ng-controller="TodoCtrl">
    <form>
        <li>Number 1: <input type="text" ng-model="one">  
        <li>Number 2: <input type="text" ng-model="two">
        <li>Total <input type="text" value="{{total()}}">       
        {{total()}}
    </form>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

javascript

function TodoCtrl($scope) {
    $scope.total = function(){
        return $scope.one * $scope.two;
    };
}
Run Code Online (Sandbox Code Playgroud)

Gre*_*Dan 40

您可以将ng-change指令添加到输入字段.看一下docs的例子.

  • 虽然这是一个有用的答案,但它有资格作为仅限链接的答案.很高兴在现场有一个例子,提到OP的具体问题...... (13认同)

Mar*_*tin 28

我猜测当你在总计字段中输入一个值时,值表达式会以某种方式被覆盖.

但是,您可以采用另一种方法:为总值创建一个字段,当更改onetwo更改该字段时.

<li>Total <input type="text" ng-model="total">{{total}}</li>
Run Code Online (Sandbox Code Playgroud)

并更改javascript:

function TodoCtrl($scope) {
    $scope.$watch('one * two', function (value) {
        $scope.total = value;
    });
}
Run Code Online (Sandbox Code Playgroud)

这里举例说明.

  • +1输入字段应始终具有关联的ng-model/$ scope属性.不应在Angular应用程序中使用"value"参数.另见http://stackoverflow.com/questions/10610282/angularjs-value-attribute-on-an-input-text-box-is-ignored-when-there-is-a-ng-m (3认同)

Jen*_*ens 5

我写了一个指令,你可以用它来将ng模型绑定到你想要的任何表达式.每当表达式更改时,模型都将设置为新值.

 module.directive('boundModel', function() {
      return {
        require: 'ngModel',
        link: function(scope, elem, attrs, ngModel) {
          var boundModel$watcher = scope.$watch(attrs.boundModel, function(newValue, oldValue) {
            if(newValue != oldValue) {
              ngModel.$setViewValue(newValue);
              ngModel.$render();
            }
          });

          // When $destroy is fired stop watching the change.
          // If you don't, and you come back on your state
          // you'll have two watcher watching the same properties
          scope.$on('$destroy', function() {
              boundModel$watcher();
          });
        }
    });
Run Code Online (Sandbox Code Playgroud)

您可以在模板中使用它,如下所示:

 <li>Total<input type="text" ng-model="total" bound-model="one * two"></li>      
Run Code Online (Sandbox Code Playgroud)