Angular指令$ compile vs event $ compile
为什么按钮点击时$编译失败? 在指令中正常工作。 我也尝试了$ 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(content);
在按钮事件中。 $ scope.elem似乎有效,所以我不确定它是什么
错误:
TypeError:无法在r处https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:151:140读取null属性'replaceChild'(https://ajax.googleapis (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular。)。 Object.S。(匿名函数)[as replaceWith](https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js:154:min.js:151:81) 73)at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26上的k。$ scope.doSomething(http://run.plnkr.co/FY9K9EgxTDQoYQgJ/main.js:15:25) /aular.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
链接地址: http://www.djcxy.com/p/77697.html上一篇: Angular directive $compile vs event $compile
下一篇: Is this an AngularJS service masquerading as a factory?