简体   繁体   English

如何使用属性参数在AngularJS中设置模型的属性?

[英]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.

相关问题 如何使用angularjs在CSS中设置body属性? - How to set body attribute in css using angularjs? 如何让AngularJS将我的模型属性设置为null而不是undefined from <select> - How do I get AngularJS to set my model property to null instead of undefined from <select> AngularJS:如何从控制器中的模型数据正确设置服务属性? - AngularJS : How do I properly set a service property from model data in a controller? 如何在angularjs中使用ng-model调用方法 - How can I call a method using ng-model in angularjs 如何绑定到AngularJS中的表单属性? - How can I bind to a form property in AngularJS? 为什么不能在Object.create()中使用属性描述符设置可写属性? - Why can't I set the writable attribute using a property descriptor in Object.create()? 如何在Javascript / AngularJS中动态设置foo等于Object Property Name? - How can I dynamically set foo equal to Object Property Name in Javascript/AngularJS? 如何显示另一个模型属性的angularjs材质验证? - How do I show angularjs material validation for another model property? 如何使用for循环在空对象中设置属性? - how can i set the property in empty object using for loop? 如何在JavaScript中传递多个参数来设置对象属性的属性? - How can I pass more than one argument to set attribute of object property in JavaScript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM