我试着写了一个小指令,用另一个模板文件包装它的内容。
这段代码:
<layout name="Default">My cool content</layout>
应该有以下输出:
<div class="layoutDefault">My cool content</div>
因为布局"Default“有这样的代码:
<div class="layoutDefault">{{content}}</div>
下面是该指令的代码:
app.directive('layout', function($http, $compile){
return {
restrict: 'E',
link: function(scope, element, attributes) {
var layoutName = (angular.isDefined(attributes.name)) ? attributes.name : 'Default';
$http.get(scope.constants.pathLayouts + layoutName + '.html')
.success(function(layout){
var regexp = /^([\s\S]*?){{content}}([\s\S]*)$/g;
var result = regexp.exec(layout);
var templateWithLayout = result[1] + element.html() + result[2];
element.html($compile(templateWithLayout)(scope));
});
}
}
});
My problem:
当我在模板中使用作用域变量时(在布局模板中或布局标签内),例如。{{whatever}}
it只在一开始就能工作。如果我更新whatever
变量,该指令将不再更新。整个链接函数将只触发一次。
我认为,AngularJS并不知道这个指令使用了作用域变量,因此它不会被更新。但我不知道如何修复这种行为。
发布于 2013-11-19 18:19:03
您应该创建一个绑定的作用域变量并观察它的变化:
return {
restrict: 'E',
scope: {
name: '='
},
link: function(scope) {
scope.$watch('name', function() {
// all the code here...
});
}
};
发布于 2014-05-20 14:44:11
对于这个问题,我也需要一个解决方案,我使用了这个帖子中的答案,得出了以下结论:
.directive('tpReport', ['$parse', '$http', '$compile', '$templateCache', function($parse, $http, $compile, $templateCache)
{
var getTemplateUrl = function(type)
{
var templateUrl = '';
switch (type)
{
case 1: // Table
templateUrl = 'modules/tpReport/directives/table-report.tpl.html';
break;
case 0:
templateUrl = 'modules/tpReport/directives/default.tpl.html';
break;
default:
templateUrl = '';
console.log("Type not defined for tpReport");
break;
}
return templateUrl;
};
var linker = function (scope, element, attrs)
{
scope.$watch('data', function(){
var templateUrl = getTemplateUrl(scope.data[0].typeID);
var data = $templateCache.get(templateUrl);
element.html(data);
$compile(element.contents())(scope);
});
};
return {
controller: 'tpReportCtrl',
template: '<div>{{data}}</div>',
// Remove all existing content of the directive.
transclude: true,
restrict: "E",
scope: {
data: '='
},
link: linker
};
}])
;
包括在html中:
<tp-report data='data'></tp-report>
此指令用于根据从服务器检索到的数据集动态加载报告模板。
它在scope.data属性上设置监视,并且每当该监视更新时(当用户从服务器请求新的数据集时),它加载相应的指令来显示数据。
发布于 2013-11-19 18:11:06
你需要告诉Angular你的指令使用了一个作用域变量:
您需要将作用域的一些属性绑定到您的指令:
return {
restrict: 'E',
scope: {
whatever: '='
},
...
}
然后$watch
它:
$scope.$watch('whatever', function(value) {
// do something with the new value
});
有关详细信息,请参阅Angular documentation on directives。
https://stackoverflow.com/questions/20068526
复制相似问题