Я хочу добавить другой экземпляр моей директивы в родительскую директиву, но я не могу использовать $ apply для перекомпиляции моей директивы.Добавление директивы внутри директивы программно
Я думаю, что я пропустил что-то где-то здесь :)
Мой HTML код
<div ng-app="TestApp">
<div ng-controller="TestCtrl">
<input ng-model="NewData" />
<button ng-click="AddNewData($event)">Add New</button>
<br /><br />
<div test-collector="testColScope" id="testCol">
<div test-data="" xx-value="Mouse" xx-href="https://fb.com"></div>
<div test-data="" xx-value="Keyboard" xx-href="https://goo.gl"></div>
</div>
</div>
</div>
Мой JavaScript код
var app = angular.module('TestApp', []);
app.controller('TestCtrl', ['$scope', function($scope){
$scope.AddNewData = function($event){
// i also want to access this but it shows undefined
console.log("test-collector", $scope.testColScope);
var div = $('<div></div>')
.attr(
{
"test-data":"",
"xx-value":$scope.NewData,
"xx-href":"http://p.com"
});
//$scope.$apply(function(){
$('#testCol').append(div);
//});
};
}]);
app.directive("testCollector", function() {
return {
restrict: "A",
scope: {
},
transclude: true,
replace: true,
controller: function($scope) {
console.log($scope);
},
link: function(scope, element, attrs) {
console.log(attrs);
scope[attrs.testCollector] = {
Enteng : 'Dagpin'
};
},
template: '<div>' +
'<ul><div ng-transclude></div></ul>' +
'</div>'
}
});
app.directive("testData", function(){
return {
restrict: "A",
require: '^testCollector',
transclude: true,
replace: true,
scope: {
xxValue: '@',
xxHref: "@"
},
template: '<li><a href="{{xxHref}}">{{xxValue}}</a></li>'
}
});
Вы не можете получить доступ к значениям testCollector из TestCtrl, потому что сборщик проб определяет новую область. Значения по областям не распространяются. – Enzey
есть ли способ сказать, как область. $ Parent [attrs.testCollector] = { Enteng: 'Dagpin' }; ? –
Вы могли бы, но это сработало бы, если бы вы удалили дочернюю область в директиве. Просто не определяйте 'scope: {}' в директиве testCollector. – Enzey