当我用按钮添加时,为什么我的ng-click不起作用?我最初加载按钮时,同样的ng-click工作正常。
app.controller('demoCtrl', function() {
this.clk = '<button ng-click="dctrl.click()">Button</button>';
this.click = function() {
alert('clicked');
}
})
app.directive('btnClick', function() {
return {
restrict: 'A',
scope: {
actionBtn: '='
},
link: function(scope, element, attrs) {
element.append(scope.actionBtn);
}
}
})
HTML
<body ng-controller="demoCtrl as dctrl">
<div btn-click action-btn="dctrl.clk"></div>
</body>
http://plnkr.co/edit/QPKXfGd9s7HzLvEfKvbG?p=preview
更新
我也尝试过这种方式,但没有运气
element.append($compile(scope.actionBtn)(scope));
答案 0 :(得分:2)
你需要compile手动为angularjs创建一个新的dom元素来处理它,所以
app.directive('btnClick', ['$compile', function ($compile) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.append($compile(scope.$eval(attrs.actionBtn))(scope));
}
}
}])
var app = angular.module('my-app', [], function() {})
app.controller('demoCtrl', function() {
this.clk = '<button ng-click="dctrl.click()">Button</button>';
this.click = function() {
alert('clicked');
}
})
app.directive('btnClick', ['$compile',
function($compile) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.append($compile(scope.$eval(attrs.actionBtn))(scope));
}
}
}
])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="my-app" ng-controller="demoCtrl as dctrl">
<div action-btn="dctrl.clk" btn-click></div>
</div>