无法从内部指令更改ng-model

时间:2015-07-15 20:43:37

标签: javascript angularjs angularjs-directive angularjs-scope angular-digest

我试图创建一个从父html标记更改ng-model的指令,但它不起作用:

var app = angular.module('myApp',[]);
app.controller('ParentController',['$scope', function($scope) {
  $scope.anyVar = "Anything";

  $scope.list = ['It doesn\'t work','It also doesn\'t work'];

}]);

app.directive('customValue', [function() {
    return {
      restrict: 'A',
      require: '^?ngModel',
      link: function(scope, element, attr, ngModel) {
          element.bind('click',function() {
              var element = angular.element(this);
              ngModel.$setViewValue(element.attr('custom-value'));
          });

          scope.$watch(function(){
              return ngModel.$modelValue;
          }, function(modelValue){
              console.log("Wow, it was changed to : " + modelValue)  
          });
      }
    };
}]);

这是我的观点:

<div ng-app="myApp">
 <div ng-controller="ParentController">
       {{anyVar}}  
     <ul ng-model="anyVar">
       <li>
            <a custom-value="111">It' not working</a>
        </li>
        <li>
            <a custom-value="222">It's not working as well</a>
        </li>
        <li>
            ----------------------
        </li>
        <li ng-repeat="item in list">
            <a custom-value="333">{{item}}</a>
        </li>
     </ul>
 </div>
</div>

如何使用和不使用ng-repeat从内部指令更新父ng模型。

我创建了FIDDLE

1 个答案:

答案 0 :(得分:6)

基本上更新ng-model或事件中的任何范围值都不会运行摘要周期,导致角度绑定不会在UI上更新,您需要通过执行scope.$apply()手动运行它。这将运行角度摘要周期,绑定将在标记上更新。

<强>代码

$scope.$apply(function(){
   ngModel.$setViewValue(123);
});

Working Fiddle