在控制器事件上重新加载指令
Reload a directive on controller event
我有一个指令,这是通过ajax上加载获取数据。但是,在控制器中的某个事件发布了一些数据之后,指令应该用新的ajax数据重新编译,以便能够反映更改。你能帮帮我吗?
我在指令中有一个编译函数,它获取数据并将其放入HTML文件中并生成标记。
然后我在控制器中有一个保存注释函数,它保存一个新的注释,因此指令获得新的数据。
compile: function(tElement, tAttrs) {
var templateLoader = $http.get(base_url + 'test?ticket=' + $routeParams.ticketid, {cache: $templateCache})
.success(function(htmlComment) {
if (htmlComment != '')
tElement.html(htmlComment);
else
tElement.html('');
});
return function (scope, element, attrs) {
templateLoader.then(function (templateText) {
if (tElement.html() != '')
element.html($compile(tElement.html())(scope));
else
element.html('<div class="no-comments comment"><p>Be the first to comment</p></div>');
});
};
}
这是指令的编译部分。我想通过一个普通的控制器事件来调用它
我会推荐@Riley Lark的响应,但正如您已经提到的,您的API返回HTML而不是JSON,以下是我的看法。
你的控制器为:
<div ng-controller="MyCtrl">
<button ng-click="save()">Save Comment</button>
<comments></comments>
</div>
myApp.controller('MyCtrl', function($scope) {
$scope.commentHTML = '';
$scope.alert = function(salt) {
alert('You clicked, My Comment ' + salt);
}
$scope.save = function() {
// this imitates an AJAX call
var salt = Math.random(1000);
$scope.commentHTML+= '<div ng-click="alert(' + salt + ')">My Comment ' + salt + '</div>';
};
});
和注释指令为:
myApp.directive('comments', function($compile) {
return {
restrict: 'E',
link: function(scope, element) {
scope.$watch(function() { return scope.commentHTML; }, function(newVal, oldVal) {
if (newVal && newVal !== oldVal) {
element.html(newVal);
$compile(element)(scope);
}
});
}
}
});
希望这能解决你的问题…
工作演示
获取所需数据后,将数据放入$scope
属性中。根据该属性定义模板,当数据返回时,它将自动更改。
<div ng-repeat="comment in comments">
{{comment}}
</div>
您不需要compile
函数或"重新加载指令"来完成此操作。你发布的解决方案是一种对angular的重新实现。看起来你想下载一个已经插入了数据的模板,但如果你把模板从数据中分离出来,让Angular在客户端插入数据,Angular会给你最大的帮助。
相关文章:
- 指令加载真的很长,检查加载时间的方法
- 在Angular JS中POST后重新加载指令方法
- 如何在控制器中加载指令
- 延迟加载角度应用程序不会加载指令
- 在加载指令模板之前加载指令 ng 包含内容
- ng-repeat中的加载指令(动态模板URL)
- ng-include 忽略加载指令
- 加载指令后运行函数
- 加载指令模板后执行 Javascript
- Meteor AngularJS应用程序未加载指令
- 不要为某些路由加载指令
- 基于值加载指令
- AngularJS在使用服务时未正确加载指令
- 加载指令时调用init函数
- 如何实现AngularJS的加载指令
- 在加载文件时显示一个加载指令
- 在加载指令模板之前没有初始化指令的作用域,导致无法加载谷歌地图
- 在控制器事件上重新加载指令
- 如何管理AngularJS中加载指令模板的404错误
- 当惰性加载指令时,它'We’我们永远不要跑步