angularjs如何动态更改临时url
angularjs how to change tempate url dynamically
我的模块中有一个指令。我想根据一个属性更改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";
};
});
}
}
});
演示:http://plnkr.co/edit/l1IysXubJvMPTIphqPvn?p=preview
解决方案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";
};
scope.$parent.templateUrl = templateUrl; // make sure that templateUrl is updated in proper scope
})
相关文章:
- 动态地改变“”的URL;添加新项目”;链接使用javascript/jquery
- 以角度管理动态URL
- javascript在动态Url中匹配并添加字符串
- 使用服务工作者动态缓存HTTP URL的包装器
- 在angularjs中动态路由url路径
- 使用JavaScript制作动态HTML页面以重定向到URL
- 在angular.js中定义动态URL的重定向
- 在混合基本 URL 下动态加载 require.js 模块
- 动态更改字体颜色和URL
- 悬停打开 DIV 时,DIV 内容应从单独的 URL 动态加载
- Safari:无法从 blob URL 动态加载视频
- 使用正确的 URL 动态创建 HTML 页面
- 在Meteor中,如何附加应用程序's的根url动态映射到图像路径
- AngularJS V1.4.7指令模板URL动态路径
- 根据url动态更改页面内容
- 更新url.动态动作与剃刀变量
- 在表单提交时向URL动态添加GET参数
- 为服务器上不存在文件的URL动态创建内容的正确方法
- 将URL动态传递给自定义SoundCloud播放器
- 使用JavaScript根据URL动态更改href上的值