2014-01-06 36 views
2

在我的自定義AngularJS google maps directive中,我有map指令和marker指令,marker指令需要map指令。AngularJS自定義指令ng-repeat,無法調用null的方法'insertBefore'

以下是我的問題的簡化版本,我不能使用ng-repeat。

<!DOCTYPE html> 
<html ng-app="testapp"> 
<head> 
<script src="http://code.angularjs.org/1.2.5/angular.js"></script> 
<script> 
var testapp = angular.module('testapp', []); 
testapp.directive('map', [ 
    function() { 
    return { 
     restrict: 'E', 
     controller: function($scope) { 
     }, 
     link: function (scope, element, attrs) { 
     element.html("this will be a map"); 
     } 
    }; 
    } 
]); 
testapp.directive('marker', [ 
    function() { 
    return { 
     require: '^map', 
     restrict: 'E', 
     link: function (scope, element, attrs, mapController) { 
     console.log('position', attrs.position); 
     } 
    }; 
    } 
]); 
function MyCtrl($scope) { 
    $scope.positions = [[39, -90],[38, -91]]; 
} 
</script> 
</head> 

<body ng-controller="MyCtrl"> 
    <map zoom="12" center="[39, -90]"> 
    <marker ng-repeat='p in positions' position="{{ p }}"></marker> 
    </map> 
</body> 
</html> 

這是這裏演示了,http://plnkr.co/edit/IN237QwEdNkdzpDaX70z?p=preview 和錯誤是,

TypeError: Cannot call method 'insertBefore' of null 
    at http://code.angularjs.org/1.2.5/angular.js:2760:14 
    at forEach (http://code.angularjs.org/1.2.5/angular.js:303:18) 
    at forEach.after (http://code.angularjs.org/1.2.5/angular.js:2759:5) 
    at Object.JQLite.(anonymous function) [as after] (http://code.angularjs.org/1.2.5/angular.js:2825:17) 
    at Object.enter (http://code.angularjs.org/1.2.5/angular.js:3906:17) 
    at http://code.angularjs.org/1.2.5/angular.js:19048:26 
    at publicLinkFn (http://code.angularjs.org/1.2.5/angular.js:5483:29) 
    at boundTranscludeFn (http://code.angularjs.org/1.2.5/angular.js:5595:21) 
    at controllersBoundTransclude (http://code.angularjs.org/1.2.5/angular.js:6189:18) 
    at ngRepeatAction (http://code.angularjs.org/1.2.5/angular.js:19046:15) 

僅此一點效果很好標記指令。
http://plnkr.co/edit/4i8Rtvk3Qu1U8JRLRAal?p=preview

我認爲當父指令有DOM操作時出現問題。 但是,由於我們使用指令,它必須操縱dom。

任何幫助,將不勝感激。

回答

4

的問題是,你與

element.html("this will be a map"); 

更換地圖(標記)的內容相反,如果你試圖將其追加將沒有問題的工作。

element.append("this will be a map"); 

Here is a JSBin

+0

謝謝,就這麼簡單。 – allenhwkim

+0

恩,我放棄了。追加作品罰款哈哈。 –