有没有办法将配置对象传递到定义为属性指令的自定义指令中?
我在 Controller 中有一个对象,我想发送给指令:
$scope.configObject = {
count: 5,
mode: 'fast',
getData: myService.getData // function of external service that avaliable in controller
}
在我的 View 中,我声明指令:
<div class='list-class' my-list='configObject'></div>
指令看起来像:
return {
restrict: 'A',
link: function(scope, elem, attrs) {
var config = angular.fromJson(attrs.myList);
}
}
我尝试使用 angular.getJson 获取配置对象 - 但它不适用于函数(可能只获取计数和模式)。 .getJson() 是获取配置的错误方式吗?
另外(我想这甚至不可能) - 有没有办法让配置对象避免访问
attrs.myList
直接地?我的意思是如果我改变指令的初始化
.directive('myList', function() { ... }) to
.directive('myCustomList', function() { ... })
我应该改变访问
attrs.myCustomList
因为 View 看起来像
<div class='list-class' my-custom-list='configObject'></div>
最佳答案
您可以使用 $parse 服务来获取配置对象。
(function(){
var directiveName = 'myList';
angular.module('YourModule').directive(directiveName,['$parse',function($parse){
return {
restrict: 'A',
link: function(scope, elem, attrs) {
var config = $parse(attrs[directiveName])(scope);
}
};
}]);
})();
关于angularjs - 棱 Angular 分明。限制 : 'A' directive. Pass 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27728712/