2013-12-21 26 views
1

HTML:爲什麼angularjs控制器未定義時,其請求第二次

<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 
[email protected](~skipped~).html:50 

問題: 1.爲什麼「addItem」被調用兩次? (如何防止第二次調用) 2.爲什麼第二次請求控制器時未定義? (它更加有趣!)

回答

0

第一次'addItem'被調用是當第一個'testSub'被鏈接的時候。第二次是當你編譯「測試」是「testSub」的「測試」環節中:

var tmpl = "<test-sub>yep</test-sub>"; 
_element.replaceWith(_compile(tmpl)(_scope)); 

測試不再存在,不存在「的addItem」。因此控制器是不確定的。

你這樣做的目的是什麼?你可以用另一種方式來做。 。 。

+0

你是什麼意思的另一種方式?我使用「$ compile」,因爲我需要根據某些條件更改已應用的模板。 – ivsn

+0

您可以使用附加控制器到div並在那裏實現'addItem'。 – alonn24

+0

「測試不再存在」 - 即使沒有「_element.replaceWith ...」也發生同樣的錯誤(只需使用var tmplCompiled = _compile(tmpl)(_ scope))。 – ivsn

相關問題