HTML:
<div ng-app="myApp">
<test>
<test-sub>nop</test-sub>
</test>
</div>
JS:
var m = angular.module('myApp', []);
m.directive('test', ['$compile', function(_compile){
return {
restrict: 'E',
controller: ["$scope", function(_scope) {
_scope.testItems = [];
this.addItem = function(_obj) {
_scope.testItems.push(_obj);
console.log('addItem');
console.log(_obj)
}
}],
link: function(_scope, _element, _attrs, _controller) {
console.log('--- test -------------------');
var tmpl = "<test-sub>yep</test-sub>";
// var tmplCompiled = _compile(tmpl)(_scope);
_element.replaceWith(_compile(tmpl)(_scope));
}
}
}]);
m.directive('testSub', ['$compile', function($compile){
return {
restrict: 'E',
require: '^?test',
controller: ["$scope", function(_scope) {
}],
link: function(_scope, _element, _attrs, _controller) {
console.log('--- testSub ----------------');
_controller.addItem({x1:'x1',y1:'y1'});
}
}
}]);
(http://jsfiddle.net/isnigirev/KF34m/)
我得到了:
--- testSub ---------------- (index):54
addItem (index):34
Object {x1: "x1", y1: "y1"} (index):35
--- test ------------------- (index):39
--- testSub ---------------- (index):54
TypeError: Cannot call method 'addItem' of undefined
or in FireFox console:
--- testSub ----------------
test_r...03.html (line 49)
addItem
test_r...03.html (line 29)
Object { x1="x1", y1="y1"}
test_r...03.html (line 30)
--- test -------------------
test_r...03.html (line 34)
--- testSub ----------------
test_r...03.html (line 49)
Error: _controller is undefined
.link@(~skipped~).html:50
问题: 1.为什么“addItem”被调用两次? (如何防止第二次调用它) 2.为什么在第二次请求时控制器未定义? (它甚至更有趣!)
答案 0 :(得分:0)
第一次调用'addItem'时,第一个'testSub'被链接。第二次是在'test'链接中将'test'编译为'testSub'时:
var tmpl = "<test-sub>yep</test-sub>";
_element.replaceWith(_compile(tmpl)(_scope));
测试不再存在且没有'addItem'。因此控制器未定义。
这样做的目的是什么?你可以用另一种方式做。 。