4

我正在尝试创建一个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)  
          });
      }
    };
}]);

这是我的看法:

<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-model。

我创建了一个FIDDLE

4

1 回答 1

6

基本上更新ng-model或来自事件的任何范围值都不会运行摘要循环,因此角度绑定不会在 UI 上更新,您需要手动运行它scope.$apply()。这将运行角度摘要循环,并且绑定将在标记上更新。

代码

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

工作小提琴

于 2015-07-15T20:46:40.237 回答