gpt4 book ai didi

javascript - 在 Controller 事件上重新加载指令

转载 作者:行者123 更新时间:2023-11-30 17:27:26 24 4
gpt4 key购买 nike

我有一个指令,它在加载时通​​过 ajax 获取数据。但是在 Controller 中发布一些数据的事件之后,指令应该使用新的 ajax 数据重新编译,以便可以反射(reflect)更改。你能帮忙吗?

我在指令中有一个编译函数,它获取数据并将其放入 HTML 文件并生成标记。

然后我在 Controller 中有一个保存评论的功能,它保存了一条新评论,因此指令获取了新数据。

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>');
});
};
}

这是指令的编译部分。我希望通过正常的 Controller 事件调用它。

最佳答案

我会推荐@Riley Lark 的回复,但正如您已经提到的,您的 API 返回 HTML 而不是 JSON,这是我的看法。

你的 Controller 是:

<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);
}
});
}
}
});

希望这能解决您的问题..!

Working Demo

关于javascript - 在 Controller 事件上重新加载指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23937127/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com