Angular directive $compile vs event $compile
Why does the $compile fail during a button click? Works fine in the directive. I also tried the $compile in an $apply function block, but that didn't work either.
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;
}
}; });
The problem, or at least error happens at: $scope.elem.replaceWith(content);
in the button event. $scope.elem seems valid, so I'm not really sure what it is
error:
TypeError: Cannot read property 'replaceChild' of null at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:151:140 at r (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:7:290) at r.replaceWith (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:151:81) at Object.S.(anonymous function) [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) at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:177:68 at 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) at HTMLButtonElement. (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:194:226) angular.js:10072
链接地址: http://www.djcxy.com/p/77698.html上一篇: 通过使用角度js选择元素项来排序列表