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

时间:2015-10-02 00:08:44

标签: javascript angularjs angularjs-directive

我正在尝试使用隔离范围创建一个指令。

我有

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'并且它未定义。我不确定我错过了什么。任何人都可以帮我吗?谢谢!

1 个答案:

答案 0 :(得分:1)

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');
                    }
                }
            );
        }
    };