【问题标题】:Using directive scope attribute value inside directive controller (not template)在指令控制器(不是模板)中使用指令范围属性值
【发布时间】:2014-12-17 17:58:29
【问题描述】:

AngularJS 的新手,我很难理解指令的一些细节。我有一个场景,我想使用不包含嵌入的指令(我认为?),使用指令的隔离控制器内的指令的属性值来获取额外的数据以提供给指令的模板......(希望满嘴的话对吗?)。

也许这个伪示例会让我更清楚我想要实现的目标:

someDirective.js:

angular.module('someDirective', [
    'someService',
])

.directive('someDirective', function() {
    function SomeController($scope, someService) {
        $scope.additionalData = someService.getStuff(/* ??? I want to use 'someKey' here */);
    }

    return {
        restrict: 'E',
        controller: SomeController,
        scope: {
            someKey: '='
        },
        template: '{{additionalData | json}}'
    };
});

directiveUser.tpl.html:

<someDirective someKey="someKeyFromTheOuterScope"/>

请注意,我的指令模板不需要直接使用键值,而是使用指令控制器提供的附加数据。

我读过的所有文档要么直接在模板中使用提供的范围属性数据,要么通过指令链接函数的“attrs”参数。我不认为链接是我想要的,因为我不是在操作 DOM,而只是想为指令的模板提供额外的数据。

我在这里从根本上误解了什么?

【问题讨论】:

    标签: angularjs-directive


    【解决方案1】:

    如果我理解正确,您可以使用范围来获取 someKey 的值...试试这个:

    angular.module('myApp', [])
    .controller('myController', function($scope) {
        $scope.outerScopeKey = 'outer scope key';
    })
    .service('someService', function() {
        this.getStuff = function(someKey) {
            return someKey;
        };
    })
    .directive('someDirective', function() {
        function SomeController($scope, someService) {
            $scope.additionalData = someService.getStuff($scope.someKey);
        }
    
        return {
            restrict: 'E',
            controller: SomeController,
            scope: {
                someKey: '='
            },
            template: '{{ additionalData | json }}'
        };
    });
    

    你的 HTML 看起来像这样:

    <div ng-controller="myController">
        <some-directive some-key="outerScopeKey"/>
    </div>
    

    所以自定义指令位于另一个控制器内部,来自控制器(外部范围)的数据被传递到指令中,然后传递到服务。

    这里是fiddle

    【讨论】:

    • 看起来我的问题是包含的 HTML 片段中的参数名称非规范化不正确(我在此处的发布是从我的实际文件中简化的)。感谢您确认我从根本上尝试做的事情与我认为的一样直截了当。
    猜你喜欢
    • 1970-01-01
    • 2015-01-11
    • 2023-03-13
    • 1970-01-01
    • 2016-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-08
    相关资源
    最近更新 更多