Javascript angularjs如何动态更改tempate url
我的模块中有一个指令。我想根据属性更改Javascript angularjs如何动态更改tempate url,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,我的模块中有一个指令。我想根据属性更改模板URL HTML 这是行不通的。templateurl未加载到div中。我想动态更改templateurl,这是可能的 非常感谢您的帮助。这在角度上不是很清楚templateUrl可以是动态构造模板URL的函数,但是在您的情况下,您需要一个作用域,该作用域在构造URL时还不可用 您可以在ngInclude的帮助下执行以下操作: app.directive('test', function() { return { restrict
模板URL
HTML
这是行不通的。templateurl
未加载到div中。我想动态更改templateurl,这是可能的
非常感谢您的帮助。这在角度上不是很清楚
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";
};
});
}
}
});
app.directive('test',function(){
返回{
限制:“A”,
范围:{
“阶段”:“=”
},
模板:“”,
链接:函数(范围、元素、属性){
范围:$watch('阶段'),功能(条件){
如果(scope.stage===‘欢迎’){
scope.templateUrl=“hello.html”;
}否则{
scope.templateUrl=“other.html”;
};
});
}
}
});
演示:解决方案1:
scope.$watch('stage', function(condition){
var templateUrl;
if(stage === 'welcome'){
templateUrl = "hello.html";
} else{
templateUrl = "someothertemplate.html";
};
//load the template;
$http.get(templateUrl)
.then(function (response) {
// template is loaded.
// add it and compile it.
angular.element(element).html(response.data);
$compile(element.contents())(scope);
});
});
解决方案2:
使用ng包括
<div test stage="dynamicstage">
<div ng-include="templateUrl"></div>
</div>
请看这篇文章:
scope.$watch('stage', function(condition){
var templateUrl;
if(stage === 'welcome'){
templateUrl = "hello.html";
} else{
templateUrl = "someothertemplate.html";
};
//load the template;
$http.get(templateUrl)
.then(function (response) {
// template is loaded.
// add it and compile it.
angular.element(element).html(response.data);
$compile(element.contents())(scope);
});
});
<div test stage="dynamicstage">
<div ng-include="templateUrl"></div>
</div>
scope.$watch('stage', function(condition){
var templateUrl;
if(stage === 'welcome'){
templateUrl = "hello.html";
} else{
templateUrl = "someothertemplate.html";
};
scope.$parent.templateUrl = templateUrl; // make sure that templateUrl is updated in proper scope
})