AngularJS - Update directive from the controller

I have a directive that includes an HTML file based on a variable area. When HTML is loaded for the first time, all is well. But when the scope variable changes ng-clic, I cannot recall the 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 a scope variable that changes to ng-click. Thanks in advance.

+4
source share
2 answers

You need to add watchto aType or some kind of event to make the code more than once (when connecting):

something like that:

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 .

+5
source

$watch(), , . ng-click @Amir Popovich , , .

: ?

+1

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


All Articles