指令中的Angular compile似乎进入无限循环

时间:2015-03-07 12:07:41

标签: javascript angularjs

我有一个动态文字指令。我希望能够使用ng-click指令从文本中调用函数。我知道这样做的最好方法是将html编译成模板。但是当我尝试这样做时,我进入了一个无限循环:

angular.module('app')
  .directive('times', ['$compile', function ($compile) {
    return {
      restrict: 'E',
      link: function postLink(scope, element, attrs) {
        scope.selectDay = function() {
          console.log("Clicked on directive");
        }

        var content = element.html("<div><span ng-click='selectDay()'>Some test content</span></div>");
        var compiled = $compile(content);
        element.append(content);
        compiled(scope);        
      }
    };
  }]);

4 个答案:

答案 0 :(得分:2)

您需要更改编译方式。首先给元素提供内容,然后使用范围编译其内容:

element.html("<div><span ng-click='selectDay()'>Some test content</span></div>");
$compile(element.contents())(scope);

Fiddle

答案 1 :(得分:2)

你的问题是你在将它附加到DOM之后编译了错误的元素, 您应首先使用scope编译新元素,然后附加到指令元素

<强> CODE

angular.module('app', [])
.directive('times', ['$compile', function($compile) {
  return {
    restrict: 'E',
    link: function postLink(scope, element, attrs) {
      scope.selectDay = function() {
        console.log("Clicked on directive");
      }

      var content = "<div><span ng-click='selectDay()'>Some test content</span></div>";
      var compiled = $compile(content);
      element.append(compiled(scope));
    }
  };
}]);

Plunkr

答案 2 :(得分:0)

以一种简单的方式,像这样:

angular.module('app').directive('times', [
    '$compile',
    function($compile) {
        return {
            restrict: 'E',
            template: '<div><span ng-click="selectDay()">test</span></div>',
            link: function(scope, element, attrs) {
                return scope.selectDay = function() {
                    return console.log('Clicked on directive');
                };
            }
        };
    }
]);

答案 3 :(得分:0)

您需要重新订购内容创建和编辑。 创建内容,然后创建编译函数,然后编译然后附加编译的内容。演示:http://jsfiddle.net/d2ayw9vz/

angular.module("app",[])
  .directive('times', ['$compile', function ($compile) {
    return {
      restrict: 'E',
      link: function postLink(scope, element, attrs) {
        scope.selectDay = function() {
          console.log("Clicked on directive");
        };

        var content = "<div><span ng-click='selectDay()'>Some test content</span></div>";
        var compiled = $compile(content);
        var linked =compiled(scope);    
        element.append(linked);



      }
    };
  }]);