如何将多个属性传递到 Angular.js 属性指令中?

我有一个属性指令限制如下:

 restrict: "A"

我需要传入两个属性: 一个数字和一个函数/回调,使用 attrs对象在指令中访问它们。

如果这个指令是一个元素指令,限制在 "E"中,我可以这样做:

<example-directive example-number="99" example-function="exampleCallback()">

但是,由于某些原因,我需要指令成为属性指令。

如何将多个属性传递到属性指令中?

120308 次浏览

这与使用元素指令的方法完全相同。您将在 attrs 对象中使用它们,我的示例通过隔离作用域使用它们进行双向绑定,但这不是必需的。如果您使用的是一个独立的作用域,那么您可以使用 scope.$eval(attrs.sample)或者只使用 scope.sample 访问这些属性,但是它们可能不会根据您的情况在链接时进行定义。

app.directive('sample', function () {
return {
restrict: 'A',
scope: {
'sample' : '=',
'another' : '='
},
link: function (scope, element, attrs) {
console.log(attrs);
scope.$watch('sample', function (newVal) {
console.log('sample', newVal);
});
scope.$watch('another', function (newVal) {
console.log('another', newVal);
});
}
};
});

用作:

<input type="text" ng-model="name" placeholder="Enter a name here">
<input type="text" ng-model="something" placeholder="Enter something here">
<div sample="name" another="something"></div>

指令可以访问在同一元素上定义的任何属性,即使指令本身不是元素。

模板:

<div example-directive example-number="99" example-function="exampleCallback()"></div>

指令:

app.directive('exampleDirective ', function () {
return {
restrict: 'A',   // 'A' is the default, so you could remove this line
scope: {
callback : '&exampleFunction',
},
link: function (scope, element, attrs) {
var num = scope.$eval(attrs.exampleNumber);
console.log('number=',num);
scope.callback();  // calls exampleCallback()
}
};
});

fiddle

如果属性 example-number的值是硬编码的,我建议使用 $eval一次,并存储该值。变量 num将具有正确的类型(一个数字)。

这对我来说很有用,我认为它更符合 HTML5。您应该将 html 改为使用“ data-”前缀

<div data-example-directive data-number="99"></div>

在指令中读取变量的值:

scope: {
number : "=",
....
},

您可以将一个对象作为属性传递并将其读入指令,如下所示:

<div my-directive="{id:123,name:'teo',salary:1000,color:red}"></div>


app.directive('myDirective', function () {
return {
link: function (scope, element, attrs) {
//convert the attributes to object and get its properties
var attributes = scope.$eval(attrs.myDirective);
console.log('id:'+attributes.id);
console.log('id:'+attributes.name);
}
};
});

如果你从另一个指令“要求”“ exampleDirective”+ 你的逻辑在“ exampleDirective”的控制器中(让我们说“ exampleCtrl”) :

app.directive('exampleDirective', function () {
return {
restrict: 'A',
scope: false,
bindToController: {
myCallback: '&exampleFunction'
},
controller: 'exampleCtrl',
controllerAs: 'vm'
};
});
app.controller('exampleCtrl', function () {
var vm = this;
vm.myCallback();
});