Is there a way to pass scope to the templateUrl: function directive?

I have a directive with which I call in a loop. Each element in the loop has an attribute FieldTypeId, and depending on the value of FieldTypeId I want to change the URL of the template. I believe this is a better and polymorphic approach, rather than executing the ng-switch statement in html.

<div ng-repeat="item in attributes"> <div attribute-input></div> </div> 

Of course, $scope not available in this directive:

 editStudentAccountModule.directive('attributeInput', function () { return { restrict: "AE", templateUrl: function () { // var attribute = $scope.attributes[$scope.$index]; if (attribute.FieldTypeId == 1) { return '../Templates/dropdown.html'; } else if (attribute.FieldTypeId == 2) { return '../Templates/radio.html'; } // etc. } } }); 
+6
source share
1 answer

You will need to load the template in the link function in order to access the area, before you access the template itself either in the template or in compilation, look here: What are the advantages of the directive template function in Angularjs?

This is obvious if you really used the $ compilation service directly. When you call $ compile on any DOM, it returns a communication function, which you then call, passing the scope to execute it. Therefore, when you see this from this point of view, it is obvious that you will have no scope until the compilation is called and the link function is returned and then called using the scope ... it looks something like this :

 $compile("<div ng-repeat='thing in things'></div>")({things:['thing1','thing2']});//Normally you would pass a scope object in here but it can really be whatever 

Here are a little put on in the dark of your code:

 editStudentAccountModule.directive('attributeInput', function () { return { restrict: "AE", scope:{info:"="}, link: function(scope){ var templateToUse = '../Templates/default.html'; if (scope.info.FieldTypeId == 1) { templateToUse '../Templates/dropdown.html'; } else if (scope.info.FieldTypeId == 2) { templateToUse '../Templates/radio.html'; } // etc. scope.myTemplate = templateToUse; }, template:"<div ng-include='myTemplate'></div>"; } }); <div ng-repeat="item in attributes"> <div attribute-input info="item"></div> </div> 
+11
source

Source: https://habr.com/ru/post/970153/


All Articles