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

nan*_*doj 4 javascript angularjs angularjs-directive angularjs-scope angularjs-digest

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

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)  
          });
      }
    };
}]);
Run Code Online (Sandbox Code Playgroud)

这是我的看法:

<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>
Run Code Online (Sandbox Code Playgroud)

如何在有和没有ng-repeat的内部指令中更新父ng模型.

我创建了一个FIDDLE

Pan*_*kar 6

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

$scope.$apply(function(){
   ngModel.$setViewValue(123);
});
Run Code Online (Sandbox Code Playgroud)

工作小提琴