以编程方式更改模型时,ngChange不起作用?

时间:2014-12-17 23:32:32

标签: javascript angularjs youtube-api

它在the docs中说ngChange不会触发:“如果模型是以编程方式更改的,而不是通过更改输入值”。

这是否意味着如果您以编程方式更改模型,则无法使用ngChange

或者是否意味着您无法使用ngChange if:

1)您以编程方式更改模型

2)您无法通过输入字段更改模型

2 个答案:

答案 0 :(得分:9)

这只是意味着如果使用javascript来更改模型,则不会评估ngChange表达式。如果你想要触发ngChange,你需要以编程方式调用类似于以下内容的表达式:

<input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />

如果你想激活它,你需要手动调用更改功能:

$scope.confirmed = 'test';
$scope.change();

答案 1 :(得分:1)

如果我正确地阅读并理解了这一点,不幸的是你不能像你说的那样用ng-change来做,但我并不是100%肯定。

我在考虑ng-model-options,这是AngularJS 1.3附带的新功能,也许这可以推动你前进。

getter和setter有一个自动选项,允许您实时更改模型。从理论上讲,您可以使用它并使用 ng-bind 调用更新函数。

也许这可以成为解决问题的可能解决方案......

&#13;
&#13;
(function(angular) {
  'use strict';
angular.module('getterSetterExample', [])
  .controller('ExampleController', ['$scope', function($scope) {
    var _name = 'Brian';
    $scope.user = {
      name: function(newName) {
        return angular.isDefined(newName) ? (_name = newName) : _name;
      }
    };
  }]);
})(window.angular);
&#13;
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-ngModelOptions-directive-getter-setter-production</title>
  

  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.7/angular.min.js"></script>
  <script src="app.js"></script>
  

  
</head>
<body ng-app="getterSetterExample">
  <div ng-controller="ExampleController">
  <form name="userForm">
    Name:
    <input type="text" name="userName"
           ng-model="user.name"
           ng-model-options="{ getterSetter: true }" />
  </form>
  <pre>user.name = <span ng-bind="user.name()"></span></pre>
</div>
</body>
</html>
&#13;
&#13;
&#13;

相关问题