我试图在AngularJS中构建一个可以重用的指令(UI滑块)。但我需要多个滑块,因此滑块的一个属性应该是它绑定的属性。我在想一个名为"属性"的属性。在更改滑块时会更新,但我不确定语法或何时进行监听,如何监听该属性。
有人能指出我正确的方向吗?
答案 0 :(得分:0)
最重要的是,您应该使用隔离范围声明您的指令,以便可以使用不同的属性值同时使用指令的多个实例。另外,要观察某些内容发生了变化,请在链接功能中添加$ 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;
});
}
}
});
在HTML中,您可以这样声明:
<slider property="person.age" />
其中person.age
是您传递给滑块的范围变量。