我有以下指令,其中有两个孩子div
。第二个div(使用angular.element
创建)应该是可以解决的。由于我是使用angular.element
创建的,因此我尝试使用ng-click
函数添加attr
,但这并不起作用。这段代码有什么问题?
app.directive('mydir', function () {
var directive = {};
directive.restrict = 'EA';
directive.replace = true;
directive.scope = {
control: '=',
};
directive.template = '<div id="root"></div>';
directive.link = function (scope, element, attrs) {
var wrap = angular.element('<div id="wrap"></div>');
element.append(wrap);
var node = angular.element('<div id="node"></div>');
node.attr('ng-click', 'toggle()'); // <--- this doesn't work
wrap.append(node);
scope.toggle = function () {
alert('clicked');
};
});
return directive;
});
答案 0 :(得分:3)
元素必须使用角度$compile
服务编译:
app.directive('mydir', function ($compile) { // added dependency here
var directive = {};
directive.restrict = 'EA';
directive.replace = true;
directive.scope = {
control: '=',
};
directive.template = '<div id="root"></div>';
directive.link = function (scope, element, attrs) {
var wrap = angular.element('<div id="wrap"></div>');
element.append(wrap);
var node = angular.element('<div id="node"></div>');
node.attr('ng-click', 'toggle()'); // <--- this doesn't work
var content = $compile(node)(scope);
wrap.append(content);
scope.toggle = function () {
alert('clicked');
};
});
return directive;
});
Here是关于使用$compile
的简短教程。希望有所帮助