我有这个指令,我正试图让它重新加载它自动获取的内容。到目前为止,运气并不好。想帮忙吗?
编辑:我已经尝试了建议的答案,但它不起作用。我收到 $digestx10 错误。
一切正常,保存正常,DOM 只是不会重新加载。
angular.module('mymodule').directive('chatContent',
["$compile",'localStorageService','loginService','peopleOnlineService',
function($compile, localStorageService, loginService, peopleOnlineService) {
var LoadData = function (data, userId) {
var template = '';
//localStorageService.IsUser(data.userId);
if(localStorageService.IsUser(userId) === true){
template = '<div class="feedItemChat"><div class="chatItem"><div class="chatMessage userChatMessage">{{content.chatMessage}}</div></div></div>';
}else{
template = '<div class="feedItemChat"><div class="chatItem"><div class="chatMessage otherChatMessage">{{content.chatMessage}}</div></div></div>';
}
return template;
};
var linker = function (scope, element) {
var data = localStorageService.LoadDataLocal(localStorageService.CheckCorrectRoom(loginService.GetUser().userId, peopleOnlineService.GetParams().userId));
scope.$watch(data, function(){
element.html(LoadData(data,scope.content.userId)).show();
$compile(element.contents())(scope);
});
};
return {
restrict: 'E',
link: linker,
scope: {
content: '='
}
};
}]);
我也想知道,如何在此处插入 html 模板而不是愚蠢的长字符串?
最佳答案
请多加注意,因为我是菜鸟,可能遗漏了一些东西...
我怀疑你在错误的地方解决了这个问题。 scope.content
(在外部范围内)是否设置在 Angular 框架之外的某个地方?如果是这样,请将 scope.content =...
包装在 $scope.$apply() 中以使框架触发任何监视。
我认为您根本不需要 $watch。当你需要触发的更改没有被 View 引用时,你只需要使用 $watch 。每个 {{expression}} 都会在该 expression 上创建一个 watch。
考虑在指令上使用单个模板,并在模板的 ng-class='...'
中包含一个“chatMessageClass”范围值。
这最大限度地减少了您和浏览器的工作量。除非代码的其余部分有一些不明显的副作用,否则一切都会消失。
var linker = function (scope, element) {
scope.chatMessageClass = localStorageService.IsUser(scope.content.userId) ?
'userChatMessage' : 'otherChatMessage';
};
引用资料: https://stackoverflow.com/a/15113029/685923 https://docs.angularjs.org/api/ng/directive/ngClass https://docs.angularjs.org/api/ng/type/ $rootScope.Scope#$apply
关于javascript - 该指令从不重新加载其内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31184985/