问题
I want to append another instance of my directive into the parent directive but i can't use $apply to recompile my directive.
I think i miss something here somewhere :)
My HTML Code
<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>
My JavaScript Code
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>'
}
});
Here is Fiddle with Problem
回答1:
To understand angular new element has been inserted you need to first compile that element using $compile
service like $compile(div)($scope)
then only you can append that element in Angular DOM.
And you directive has already rendered on html, so the div structure is changed.
instead of doing $('#testCol') use angular.element('#testCol ul div')
Here is Working Fiddle
Update 1
As per @enzey DOM manipulation should not be done inside controller. It should be done inside directive. That's why @Vincent & I made the changes in fiddle. DOM manipulation logic has been moved to inside directive.
Here is Updated Fiddle
回答2:
You are attempting DOM manipulation from within a controller. Changing the DOM is the purpose of directives. That is the first thing you need to address.
As for adding a directive to a child element in DOM you just need to use the compile function of a directive.
Module.directive('name', function () {
return {
compile: function ($element, $attrs) {
\\ here
}
}
}
来源:https://stackoverflow.com/questions/28019280/adding-directive-inside-the-directive-programatically