在我的指令中,我有以下代码,这些代码将用于不断附加到 html 元素。
//Establishes the type of question and therefore what should be displayed
app.directive('questionType', function ($http, $compile) {
return {
restrict: 'A',
link: function (scope, element, attr, model) {
switch (scope.Question.inputType) {
case 'checkbox':
//element.append('<input type="checkbox" ng-model="Question.checked"/><button ng-if="input.checked" >X</button>');
break;
case 'text':
element.append('<button class="btn btn-info" ng-click="selectProperties()" title="Assign this user"><span class="glyphicon glyphicon-user"></span>Assignment</button>');
break;
}
}
};
});
因此,当我单击按钮时,应该调用 selectproperties 函数,该函数位于要附加的元素周围的 Controller 内。但是它没有被调用,而且我知道该函数可以正常工作,因为如果我将此按钮代码直接放入 html 页面中,它就会正常工作。
我已经看到使用 $compile 是解决这个问题的一种方法,但是当我使用它时它只会导致我的网页卡住,并且控制台中不会出现任何错误。
我尝试了其他几种方法,例如将带有该方法的 Controller 添加到我的指令中 -
controller: function ($scope, $element) {
$scope.selectProperties = function () {
aler('test');
}
}
但这也没有用。而且我需要能够使用函数调用来更新我的主 Controller 中的对象,所以我不确定我是否可以那样做。
有什么想法吗?
最佳答案
您应该编译
html 以将指令
(如ng-click
)绑定(bind)到作用域属性。其他副 Angular 指令不会绑定(bind)到范围属性。
var strElm = '<button class="btn btn-info" ng-click="selectProperties()" title="Assign this user"><span class="glyphicon glyphicon-user"></span>Assignment</button>';
var compiledHtml = $compile(strElm);
element.append(compiledHtml);
并且不要从指令中删除$compile
服务,
你的代码应该是这样的,
//Establishes the type of question and therefore what should be displayed
app.directive('questionType', function($http, $compile) {
return {
restrict: 'A',
link: function(scope, element, attr, model) {
switch (scope.Question.inputType) {
case 'checkbox':
//element.append('<input type="checkbox" ng-model="Question.checked"/><button ng-if="input.checked" >X</button>');
break;
case 'text':
var strElm = '<button class="btn btn-info" ng-click="selectProperties()" title="Assign this user"><span class="glyphicon glyphicon-user"></span>Assignment</button>';
var compiledHtml = $compile(strElm);
element.append(compiledHtml);
break;
}
}
};
});
关于AngularJS:在 element.append 中添加 ng-click,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51171323/