在控制器事件上重新加载指令

Reload a directive on controller event

本文关键字:加载 指令 新加载 控制器 事件      更新时间:2023-09-26

我有一个指令,这是通过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会给你最大的帮助。