如何在我的例子中设置我的Angular指令

How to setup my Angular directive in my case?

本文关键字:我的 设置 Angular 指令      更新时间:2023-09-26

我正在尝试创建一个具有隔离作用域的指令。

angular.module('myApp').directive('itemCollection',  
['$cookies',     
    function($cookies) {
        return {
            restrict: 'E',
            scope: {
                items: '='
            },
            link: function(scope) {
                    console.log(scope.items)
                    console.log(items)
                    --> both console.log show undefined
            }
        };
    }
]);
Html

<item-collection items="item1"></item-collection>

我似乎不能得到'item1'在我的指令,它是未定义的。我不知道我错过了什么。有人能帮我一下吗?谢谢!

item1是否异步来?如果是,你需要在你的指令中设置一个手表,并在它可用时尽快处理。

    return {
        restrict: 'E',
        scope: {
            items: '='
        },
        link: function(scope) {
                console.log(scope.items)
                console.log(items)
                --> both console.log show undefined
            scope.$watch(
                function() { return scope.items; },
                function(newValue) {
                    if (newValue != null) {
                        console.log('not null:' + newValue);
                    }
                    else {
                        console.log('still null, skip');
                    }
                }
            );
        }
    };