Angular指令$ compile vs event $ compile

时间:2014-11-02 14:17:34

标签: angularjs

为什么$ click在单击按钮时失败?在指令中正常工作。我还在$ apply函数块中尝试了$ compile,但这也没有用。

http://plnkr.co/edit/rB5zteYTZ2L1WB5RzlHg

的index.html

<body ng-app="MyApp" ng-controller="MainController">
  {{message}}
  <div my-content>
  </div>
  <script src="main.js"></script>
</body>

main.js

var app=angular.module('MyApp', [])
  .controller('MainController', 
    function($scope, $rootScope, $compile) {
      $scope.label="| LABEL 1";
      $scope.elem={};
      $scope.message="";
      $scope.doSomething = function(){
        $scope.message = "should read TITLE 2 | LABEL 2 ---->";
        $scope.label="| LABLE 2";

        $scope.activeTemplate = $scope.template2;

        var linkFn = $compile($scope.activeTemplate);
        var content = linkFn($scope);
        $scope.elem.replaceWith(content);

      };
      $scope.activeTemplate="<button ng-click='doSomething()'>TITLE 1 {{label}}</button>";
      $scope.template2="<button ng-click='doSomething()'>TITLE 2 {{label}}</button>";
    }
  );

app.directive("myContent", function($compile){
return {
    link: function(scope, element){
        var template =scope.activeTemplate;
        var linkFn = $compile(template);
        var content = linkFn(scope);
        element.replaceWith(content);
        scope.elem=element;
    }

}; });

问题,或至少错误发生在:     $ scope.elem.replaceWith(内容);

按钮事件中的

。 $ scope.elem似乎有效,所以我不确定它是什么

错误:

TypeError:无法读取属性&#39; replaceChild&#39;为null     在https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:151:140     在r(https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:7:290)     在r.replaceWith(https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:151:81)     at Object.S。(匿名函数)[as replaceWith](https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:154:73)     at k。$ scope.doSomething(http://run.plnkr.co/FY9K9EgxTDQoYQgJ/main.js:15:25)     在https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:177:68     在f(https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:194:174)     at k。$ eval(https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:112:68)     at k。$ apply(https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:112:346)     在HTMLButtonElement。 (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:194:226)angular.js:10072

0 个答案:

没有答案