如何根据指令控制器中的值修改指令的模板 URL

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

本文关键字:指令 URL 修改 指令控制器 何根      更新时间:2023-09-26

我有以下AngularJS指令及其控制器。

我想根据关联控制器中aBaC的整数值设置templateURL,而不是直接在指令的template字段中输入 HTML。

如果aB + ac >= 10,我希望它使用foo.html否则我希望它使用bar.html。我该怎么做?

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);
});

指令的template/templateUrl选项在创建指令范围之前被计算。所以基本上你不能在函数templateUrl那里得到范围变量。

但是,是的,您可以通过在那里使用 ng-include 指令来解决此问题,表达式将根据范围变量值动态创建 URL。

命令

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>'
    };
  }
);

你可以改用ngInclude:

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);
});