我的模块中有一个指令。我想根据属性更改 templateUrl
。
HTML
<div test stage="dynamicstage"></div>
模块
angular.module('trial', [])
.controller('trialCtrl', function ($scope) {
$scope.dynamicstage = 'Welcome';
})
.directive('test', function () {
return {
restrict: 'A',
scope: {
'stage': '='
},
link: function (scope, element, attrs) {
scope.$watch('stage', function(condition){
if(stage === 'welcome'){
templateUrl: "hello.html";
}else{
different template url...
};
});
}
}
});
这是行不通的。 templateurl
未加载到 div 中。我想动态更改 templateUrl 这可能吗?
感谢任何帮助。
最佳答案
这在 Angular 中不是很透明。 templateUrl
可以是动态构建模板 URL 的函数,但是在您的情况下,您需要一个范围,在构建 URL 时尚不可用。
你可以在 ngInclude
的帮助下做这样的事情:
app.directive('test', function() {
return {
restrict: 'A',
scope: {
'stage': '='
},
template: '<div ng-include="templateUrl"></div>',
link: function(scope, element, attrs) {
scope.$watch('stage', function(condition) {
if (scope.stage === 'Welcome') {
scope.templateUrl = "hello.html";
} else {
scope.templateUrl = "other.html";
};
});
}
}
});
关于javascript - angularjs如何动态更改模板url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28717328/