简体   繁体   中英

Angular directive breaks scope?

First off, I'm new to Angular, and realize that I may be missing a core concept...

Consider the jsfiddle: http://jsfiddle.net/D4dFv/

I'd like to be able to click on each link, and see the {{driveState.currentView}} update in the DOM.

Everything works fine until I add in a directive that helps me detect when all images on the page have loaded successfully. With that directive in place, the binding appears to break, and you can no longer click on each link and see driveState.currentView update.

Why is this?

To test this in the jsfiddle, note that the following works fine: <img width='10' height='10' src='http://www.w3schools.com/images/pulpit.jpg'>

...and this breaks the data binding somehow: <img imageonload width='10' height='10' src='http://www.w3schools.com/images/pulpit.jpg'>

Thanks in advance.

The reason is that the Directive is defining its own controller. This makes a new instance of the controller class and is somehow messing up the scope.

To fix, take out the controller: 'Ctrl', in the Directive definition.
Here is the new Directive code:

myApp.directive('imageonload', function () {

    return {
        restrict: 'A',
        link: function ($scope, element) {

            element.bind('load', function () {

                _viewsLoaded++;
                if (_viewsLoaded === $scope.appViews.length) {
                    alert('init layout here');
                }
            });
        }
    };
});

And an updated fiddle for you.

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