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
source
share