Multiple directives [myPopup, myDraggable] asking for new/isolated scope

后端 未结 7 717
情书的邮戳
情书的邮戳 2020-12-02 18:21

I wrote a directive for dialogs (myPopup) and another one for dragging this dialog (myDraggable), but I allways get the error:

Multiple directives [m

7条回答
  •  猫巷女王i
    2020-12-02 18:45

    There is a way to work around it.

    You will not isolate scope of the directive, instead of it, we will create a new isolated scope using $new method . This method creates a new child scope, if you use true at 1st parameter it will create an isolated scope:

    If true, then the scope does not prototypically inherit from the parent scope. The scope is isolated, as it can not see parent >scope properties. When creating widgets, it is useful for the widget to not accidentally read parent state.

    But it isn't a problem because we have access to private scope by the directive link function, so is possible to work parallel with "parent" and isolated scope into a very close behavior of a directive with an isolated scope.

    Se the example bellow:

    app.directive('myDraggable', ['$document',
        function ($document) {
        return {
            restrict: 'A',
            replace: false,
            scope: false,
            //scope: { enabled: '=myDraggable', oneWayAttr: "@" }, //Just for reference I introduced a new 
            link: function(parentScope, elem, attr) {
            var scope = parentScope.$new(true); //Simulated isolation.
                scope.oneWayAttr = attr.oneWayAttr; //one-way binding @
                scope.myDraggable = parentScope.$parent.$eval(attr.myDraggable);
    
                scope.watchmyDraggable = function () {
                        return scope.myDraggable = parentScope.$parent.$eval(attr.myDraggable); //parent -> isolatedscope
                };          
                scope.$watch(scope.watchmyDraggable, function(newValue, oldValue) {
                 //(...)
                });
    
                parentScope.innerScope = scope; //If you need view access, you must create a kind of symbolic link to it.
    
            //(...)
            }
    

    I developed this work around to a validation directive, that's works very well.

提交回复
热议问题