[英]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',
scope: {
dirModel: '='
},
template: '<div><button ng-click="decrement()">-</button>' +
'<div ng-model="dirModel">{{ 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;
}
}
};
});
I am using like this 我这样用
<my-dir dirModel="user.interval"></my-dir>
Now when i click on edit form where my scope already have user.interval = 30
then that does not get set. 现在,当我单击编辑表单时,我的作用域已经有user.interval = 30
那么就不会设置。
For new form it works ok 对于新表格,它可以正常工作
working: http://plnkr.co/edit/jjIgVA?p=preview 工作: http : //plnkr.co/edit/jjIgVA?p = preview
Things you are doing wrong: 你做错了什么:
in the view you need to set the dirModel as dir-model 在视图中,您需要将dirModel设置为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) 在指令中你需要等待dirModel编译然后将其设置为scope.value(你永远不会声明它,你可能会尝试在div中错误地使用ng-model)
app.directive('myDir', function () { 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 value
var watcher = scope.$watch('dirModel', function() {
if(scope.dirModel === undefined) return;
scope.value = scope.dirModel;
watcher();
});
}
};
}); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.