Cannot change ng model from internal directive

I am trying to create a directive that modifies ng-modelfrom the parent html tag but does not work:

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)  
          });
      }
    };
}]);

It's my opinion:

<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 not working as well</a>
        </li>
        <li>
            ----------------------
        </li>
        <li ng-repeat="item in list">
            <a custom-value="333">{{item}}</a>
        </li>
     </ul>
 </div>
</div>

How to update parent ng-model from internal directive with and without ng-repeat.

I created FIDDLE

+4
source share
1 answer

Basically, updating ng-modelor any value of an area from events will not start the digest cycle, as a result, the angular binding will not be updated in the user interface, you need to start it manually by doing it scope.$apply(). This will start the angular digest loop, and the binding will be updated according to the markup method.

the code

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

Working script

+6

Source: https://habr.com/ru/post/1598120/


All Articles