How Can I Use Ng-model With Directive In Angular Js
I have this directive to increment and decrement variable like this angular.module('shopping') .directive('myDir', function () { return { restrict: 'AE',
Solution 1:
working: http://plnkr.co/edit/jjIgVA?p=preview
Things you are doing wrong:
in the view you need to set the dirModel as dir-model
in the directive you need to wait for dirModel to compile and then set it to scope.value (you never declare it, you may trying to use ng-model in the div incorrectly)
app.directive('myDir', function () {
return {
restrict: 'AE',
scope: {
dirModel: '='
},
template: '<div><button ng-click="decrement()">-</button><div>{{ value }}</div><button ng-click="increment()">+</button></div>',
link: function (scope, iElement, iAttrs) {
scope.increment = function () {
scope.value += 20;
}
scope.decrement = function () {
scope.value -= 20;
}
// wait for variable to compile, set it to your valuevar watcher = scope.$watch('dirModel', function() {
if(scope.dirModel === undefined) return;
scope.value = scope.dirModel;
watcher();
});
}
};
});
Post a Comment for "How Can I Use Ng-model With Directive In Angular Js"