Найдите здесь скрипку http://jsfiddle.net/UxYLa/6/
Это упрощенная форма того, что я пытаюсь сделать. Существует две директивы, а вложенная - subDirective
, которая динамически создает html-форму на основе выбора (случайного). Если вы нажимаете несколько раз на кнопку, она выдает ниже ошибки
TypeError: Cannot call method 'insertBefore' of null
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js:138:283
at q (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js:7:332)
at q.after (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js:138:258)
at Object.O.(anonymous function) [as after] (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js:139:414)
at Object.enter (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js:141:226)
at Object.move (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js:141:360)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js:185:282
at Object.fn (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js:99:371)
Я нашел ссылку об этом https://groups.google.com/forum/#!msg/angular/dNra_7P2hwU/09-UBn1XxyUJ https://github.com/angular/angular.js/issues/2151, но я использую последнюю стабильную версию.
В чем причина этой ошибки.
Полный код ниже:
script:
var myApp = angular.module('myApp', [])
.controller('TestController', ['$scope', function ($scope) {
$scope.data = [{ type: "a", values: [{name:"aa"}, {name: "bb"}]},
{ type: "b", values: [{name:"aa"}, {name: "bb"}]}]
}]);
myApp.directive('directive', function () {
return {
scope: {
data: "=",
},
restrict: 'E',
controller: function ($scope, $element, $attrs) {
$scope.random = function(){
$scope.model = $scope.data[Math.floor(Math.random()*$scope.data.length)];
console.log($scope.model)
};
},
template: '<div><button ng-click="random()">Random</button><sub-directive data="model"></sub-directive></div>'
};
});
myApp.directive('subDirective', function ($templateCache, $compile) {
return {
scope: {
data: "=",
},
restrict: 'E',
link: function (scope, element, attrs) {
scope.$watch('data', function (newVal, oldVal) {
if (newVal) {
element.html($templateCache.get(newVal.type + '.html'));
$compile(element.contents())(scope);
}
});
}
};
});
HTML
<script type="text/ng-template" id="a.html">
a.html
</script>
<script type="text/ng-template" id="b.html">
<div ng-repeat="itm in data">
<span ng-if='"string" == itm.type'>
<input name='{{itm.Name}}'id='{{itm.Name}}' ng-model='model[itm.Name]' type='text'></input>
</span>
</div>
</script>
<div ng-controller="TestController">
<directive data="data"></directive>
</div>