简体   繁体   中英

How to setup my Angular directive in my case?

I am trying to create a directive with isolate scope.

I have

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>

I can't seem to get the 'item1' in my directive and it's undefined. I am not sure what I am missing. Can anyone help me about it? Thanks!

Does item1 come asynchronusly? If it is, you need to set up a watch in your directive and process as soon as it is available.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM