javascript - AngularJS : Directive transcluded scope lost -


i’m building directive, i’m calling ‘requires-authorization’ wrap ng-if directive. i’d use follows:

<requires-authorization role='superuser'> <!— super secret user stuff goes here, within    scope of view's controller —> </requires-authorization> 

i’ve gotten far as:

angular.module('myapp').directive('requiresauthorization', function() {    return {     template: '<div ng-if=\'iaminrole\' ng-transclude></div>',     restrict: 'e',     transclude: true,     scope: {         role: '@'     },     controller: function($scope, userservice) {        $scope.iaminrole = (usersservice.myroles.indexof($scope.role) !== -1);     }   }; }); 

this works, content contained within directive loses scope, scope of controller of view it's found within. overlooking?

jsfiddle reference: http://jsfiddle.net/hbamg/8/ notice how auth value isn't displayed inside directive, available outside directive.

both ng-if , ng-transclude directives perform transclusion in directive. in case build-in transclude mechanism not work fine , should implement ngif of make work expected:

javascript

app.directive('requiresauthorization', function () {     return {         template: '<div ng-transclude></div>',         restrict: 'e',         transclude: true,         scope: {             role: '@'         },         controller: function ($scope) {             $scope.iaminrole = true;         },         link: function(scope, element, attr, ctrl, transcludefn) {             transcludefn(function(clone) { // <= override default transclude                 element.empty();                 if(scope.iaminrole) { // <= implement ngif                   element.append(clone);                 }             });         }     }; }); 

plunker: http://plnkr.co/edit/lnipojg786o0gvooro4z?p=preview

if ng-show option use instead of ng-if may simple workaround well. side effect hidden data presented in dom , hidden using css .ng-hide {display: none !important;}.

jsfiddle: http://jsfiddle.net/wfgxh/3/

this post may useful since describes similar issue: https://stackoverflow.com/a/22886515/1580941


Comments

Popular posts from this blog

c++ - How to add Crypto++ library to Qt project -

jQuery Mobile app not scrolling in Firefox -

How to use vim as editor in Matlab GUI -