Angularjs – Multiple directives asking for new / isolated scope

angularjsangularjs-directiveangularjs-scope

I have a directive to call a function only after iframe is loaded. However I get multidirective new / isolated scope error. My code snippet is as below.

<iframe ng-src="{{src}}" ng-if="loginCheck" ng-show="false" data-iframe-on-load="iframeOnLoad" data-iframe-callback="testLoad()"></iframe>

js:

directive('iframeOnLoad', function () {
    return {
        restrict: 'A',
        scope: {
            callback: '&iframeCallBack'
        },
        link: function (scope, element, attrs) {
            element.on('load', function() {
                return scope.callback();
            });
        }
    };
})

controller:

$scope.loginCheck = true;
$scope.testLoad= function () {
    alert('loaded...');
};

Error:

Error: [$compile:multidir] Multiple directives [iframeOnLoad, iframeOnLoad] asking for new/isolated scope on

Best Answer

There is no issue with the code you posted except &iframeCallBack should be &iframeCallback. Otherwise consider changing data-iframe-callback="testLoad()" to data-iframe-call-back="testLoad()".

The possible reason of the issue is that you have multiple directives that you create by copy-pasting an existing code of the directive and forgot to change the name of the directive to new one. Just search in your code for iframeOnLoad, I'm pretty sure you will find two directives with such name.

It is happening because AngularJS allows to register multiple directives with the same name. This pattern may be used to extend existing functionality of directive. However, you can create only one isolated scope for one DOM element, therefore two directives with the same name that require isolated scope are contradicting.

Working example see here.

The same issue as yours reproduced here.