如何从控制器动态更改指令的templateUrl

时间:2015-01-25 17:26:49

标签: javascript angularjs

我想从控制器" ServerController"传递appUmod指令的templateUrl。这样,相同的指令可以用于具有不同模板的不同模态。所以我已经将网址作为" app-modal"的属性。 server_group.html视图中使用的标记。我从指令的templateUrl属性返回该url。但它抛出了以下错误 -

TypeError: Cannot read property 'protocol' of undefined
at urlIsSameOrigin (http://localhost/js/:30578:17)
at $http (http://localhost/js/:24316:23)
at Function.$get.$http.(anonymous function) (http://localhost/js/:24533:18)
at compileTemplateUrl (http://localhost/js/:23130:13)
at applyDirectivesToNode (http://localhost/js/:22755:24)
at compileNodes (http://localhost/js/:22354:15)
at compileNodes (http://localhost/js/:22366:15)
at compile (http://localhost/js/:22287:15)
at compile (http://localhost/js/:38714:15271)

莫代尔指令 -

 angular.module("app")

    .directive("appModal", function() {
        return {
            restrict: "E",
            replace: true,
            scope: {
                modal: "=modalBody"
            },
            templateUrl: function(element, attrs) {
                return attrs.templateUrl;                  
            }                
        };

    });

控制器 -

function ServerController($scope) {

    $scope.confirmDelete = {

        body: "Are you sure you want to delete?",
        primaryBtn: "Delete",
        cancel: "Cancel",
        templateUrl: "pages/DRaaS/app/ServerGroup/partials/app_modal.html"

    };

}

Html -

<app-modal modal-body="confirmDelete" templateUrl="pages/DRaaS/app/ServerGroup/partials/app_modal.html"><app-modal>

1 个答案:

答案 0 :(得分:2)

templateUrl函数运行时,范围不可用且属性值仍未插值。所以,如果你有类似的东西:

<foo param="{{a}}"></foo>

然后在templateUrl中,您将获得"{{a}}"的字符串attrs.param - 而不是$scope.a的值。

相反,您需要接受模板url作为变量(理想情况下通过隔离范围)到指令。在指令中,您可以廉价地使用绑定到该值的ng-include

.directive("appModal", function() {
  return {
    restrict: "E",
    replace: true,
    scope: {
      modal: "=modalBody",
    },
    template: '<div ng-include="modal.templateUrl"></div>'
  };
});

根据您的建议使用:

<app-modal modal-body="confirmDelete"></app-modal>

在控制器中:

$scope.confirmDelete = {
  // other properties,
  templateUrl: "path/to/template.html"
}