Saqib Ali
Saqib Ali

Reputation: 12545

How can I modify my directive's templateURL based on values within its controller?

I have the following AngularJS directive and its controller.

Instead of entering the HTML right into the directive's template field, I would like to set the templateURL based on values of integers aB and aC in the associated controller.

If aB + ac >= 10, I want it to use foo.html otherwise I want it to use bar.html. How can I do that?

myApp.directive('myDirective',function(){
    return {
      restrict:'E',
      scope: {
        myObject: '='
      },
      controller: 'myDirectiveCtrl',
      controllerAs: 'myDrCtrl',
      bindToController: true,
      template: 'aB={{myDrCtrl.myObject.aB}} aC={{myDrCtrl.myObject.aC}}'

    };
  }
);

myApp.controller('myDirectiveCtrl', function($scope){
    var self = this;
    $scope.$watch(function() {return self.myObject}, function (objVal) {
        console.log("watch fired");
        console.log('objVal.aB = ', objVal.aB);
        console.log('objVal.aC = ', objVal.aC);
    },true);

});

Upvotes: 0

Views: 34

Answers (2)

Pankaj Parkar
Pankaj Parkar

Reputation: 136134

template/templateUrl option of directive gets evaluated before directive scope gets created. So basically you can't get scope variable over there inside templateUrl function.

But yes you could solve this problem by using ng-include directive there, with expression will create a URL dynamically based on scope variable values.

Directive

myApp.directive('myDirective',function(){
    return {
      restrict:'E',
      scope: {
        myObject: '='
      },
      controller: 'myDirectiveCtrl',
      controllerAs: 'myDrCtrl',
      bindToController: true,
      template: '<ng-include src="(aB + ac >= 10) ? \'foo.html\': \'bar.html\'"></ng-include>'
    };
  }
);

Upvotes: 2

Camille Wintz
Camille Wintz

Reputation: 951

You could use ngInclude instead:

myApp.directive('myDirective',function(){
    return {
      restrict:'E',
      scope: {
        myObject: '='
      },
      controller: 'myDirectiveCtrl',
      controllerAs: 'myDrCtrl',
      bindToController: true,
      template: '<div ng-include="myObject.currentPath"></div>'

    };
  }
);

myApp.controller('myDirectiveCtrl', function($scope){
    var self = this;
    $scope.$watch(function() {return self.myObject}, function (objVal) {
         objVal.currentPath = 'bar.html';
         if(objVal.aB + objVal.aC >= 10){
             objVal.currentPath = 'foo.html';
         }
    },true);
});

Upvotes: 1

Related Questions