4

i've a directive that include an HTML file based on a scope variable. When HTML is loaded first time all is good. But when scope variable change by ng-clic i'm not able to recall directive.

Here is my directive:

my.directive('myType', function() {
return {
    restrict: 'A',
    replace: true,
    link: function($scope, element, attrs) {          
          var myHTML;
          if ($scope.aType==1) myHTML = "aaaa";
          if ($scope.aType==2) myHTML = "bbbb"; 

          $scope.contentUrl = 'library/template/tmp-' + myHTML + '.html';
    },
    template: '<div ng-include="contentUrl"></div>'
}});

$scope.aType is scope variable that change on ng-click. Thanks in advance.

2 Answers 2

7

You need to add a watch on aType or some kind of event to make you code run more than once(on linking):

something like this:

link: function($scope, element, attrs) {       
         $scope.$watch('aType', function(newVal, oldVal){
                   var myHTML;
                   if ($scope.aType==1) myHTML = "aaaa";
                   if ($scope.aType==2) myHTML = "bbbb"; 
                   $scope.contentUrl = 'library/template/tmp-' + myHTML + '.html';
         });   
    }

JSFIDDLE.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Amir. But now also first time template doesn't load (directive don't call ng-include in template)
1

I would avoid using $watch() if you can, which you almost always can. You can always setup ng-click to pass variables from your directive to your controller, or modify @Amir Popovich's answer to do the logic in your controller, and not in the link function.

For an example on how to access methods in a directive from a controller check out: Access parent controller methods from directive?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.