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 を更新するにはどうすればよいですか。

フィドルを作成しました

4

1 に答える 1

6

基本的ng-modelに、イベントからの更新またはスコープ値はダイジェスト サイクルを実行しないため、UI で角度バインディングが更新されないため、手動で実行する必要がありますscope.$apply()。これにより、angular ダイジェスト サイクルが実行され、バインドがマークアップで更新されます。

コード

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

働くフィドル

于 2015-07-15T20:46:40.237 に答える