angularjs - 棱 Angular 分明。限制 : 'A' directive. Pass 对象

标签 angularjs angularjs-directive

有没有办法将配置对象传递到定义为属性指令的自定义指令中?

我在 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/

相关文章:

angularjs - 如何将 Angular 2 与 NetBeans 一起使用?

android - 使用 ionic 在屏幕上显示手机的地理位置

javascript - 使用菜单偏移量自定义 Angular SlideAndPush 指令

angularjs - 等待加载 Angularjs ng-controller,直到父级 Controller 完成

javascript - 我收到类型错误 : transclude is not a function and also can't able to bind select options value in select2 in angularjs

javascript - 获取 AngularJS 指令中的模板元素

javascript - 为什么 angular-ui-grid 中的 gridApi.on.edit.beginCellEdit 无法立即更新新的下拉选项?

javascript - 如何在 AngularJS 自己的指令中使用 ng-class 和函数?

javascript - ng-include 中使用的指令不起作用

javascript - 如何从 Controller 内的javascript函数调用 Angular 范围函数