[英]How can I set a property of a model in AngularJS using an attribute parameter?
I'm trying to build a directive in AngularJS that can be reused (a UI slider). 我正在尝试在AngularJS中构建可重复使用的指令(UI滑块)。 But I need multiple sliders, so one attribute of the slider should be the property that it is bound to.
但是我需要多个滑块,因此滑块的一个属性应该是绑定到的属性。 I was thinking of having an an attribute called "property" which on changing the slider would then get updated, but I'm not sure of the syntax or when doing the listen, how to listen on that property.
我当时在考虑有一个名为“属性”的属性,该属性在更改滑块时会被更新,但是我不确定语法或在进行侦听时如何监听该属性。
Can anyone point me in the right direction? 谁能指出我正确的方向?
The most important thing is that you should declare your directive with isolate scope so that multiple instances of your directive can be used at the same time with different property values. 最重要的是,您应该使用隔离范围声明指令,以便可以同时使用具有不同属性值的指令的多个实例。 In addition, to watch when something has changed, put a $watcher in your link function:
此外,要观察何时发生了更改,请在链接函数中放置一个$ watcher:
.directive("slider, function(){
return {
restrict : 'AE',
scope : {
property : '='
},
template : '.... your template....',
link : function(scope, elem, attr){
... other code if you have it...
// Watch for changes in the property variable
scope.$watch('property', function(newVal){
console.log('Do something with ' + newVal;
});
}
}
});
In the HTML, you would declare it like this: 在HTML中,您可以这样声明:
<slider property="person.age" />
Where person.age
is a scope variable that you're passing into the slider. 其中
person.age
是要传递到滑块的作用域变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.