我的控制器定义为:
broConsoleApp.controller('actionCreateController', ['$scope', '$stateParams', '$sce', function ($scope, $stateParams, $sce) {
$scope.html = "";
var resp = [];
var params = {};
/* lot of other things here */
$scope.getHtml = function (type) {
$scope.html = "";
$.get(apiHost + "/action/type/defn/" + type).success(function (response) {
resp = response['RESPONSE']['ActionsParams']['param'];
console.log(resp);
if (resp instanceof Array) {
resp.forEach(function (entry) {
$scope.html = $scope.html + $.hbs("/web/templates/actionCreate.hbs", entry);
});
}
else
$scope.html = $scope.html = $scope.html + $.hbs("/web/templates/actionCreate.hbs", resp);
$scope.$apply(function () {
$scope.html = $sce.trustAsHtml($scope.html);
});
})
.error(function (jqXHR, textStatus, errorThrown) {
console.log("Failed to fetch XML.")
});
};
$scope.add = function(){
console.log(" entered add ...");
var $key = $("<input type='text' class='input-small form-control' placeholder='Key'>");
var $value = $("<input type='text' class='input-small form-control' placeholder='Value'>");
$('form #'+name).append($key);
$('form #'+name).append($value);
};
}]);
我的获取HTML函数获取所有HTML并将其呈现为JSON。我的.hbs文件如下:
{{#if_eq type "MAP_VALUED"}}
<div class="col-lg-10 col-lg-offset-1 MAP_VALUED" id="{{name}}">
<label class="control-label col-lg-3">{{label}}</label>
<form class="col-lg-9 controls form-inline">
<input type="text" class="input-small form-control" placeholder="Key">
<input type="text" class="input-small form-control" placeholder="Value">
<button type="button" class="btn btn-primary pull-right" ng-click="add()">+</button>
</form>
<br><br>
</div>
{{/if_eq}}
这里我想要一个onClick动作来调用控制器中定义的方法$scope.add()
。 “+”按钮基本上添加了新的键值表单。
我将这个呈现的HTML绑定为:
<div ng-app="broConsoleApp" ng-controller="actionCreateController">
<div ng-bind-html="html"></div>
</div>
由于渲染的HTML最终是在broConsoleApp下定义的,因此ng-cick应该可以正常工作吗?好吧它不起作用。有人可以帮助我吗?即使我在onClick上使用jquery方法或者如何在不创建新文件的情况下使用jquery方法。我希望它在我的控制器中。 从早上起就被困住了。
答案 0 :(得分:1)
请查看工作示例:https://jsfiddle.net/Shital_D/oyx0fd6e/3/
HTML
<div ng-app="broConsoleApp" ng-controller="actionCreateController">
<div compile="html"></div>
</div>
创建指令
app.directive('compile', function ($compile) {
return function (scope, element, attrs) {
scope.$watch(
function (scope) {
return scope.$eval(attrs.compile);
},
function (value) {
element.html(value);
$compile(element.contents())(scope);
}
);
};
});
和 控制器
app.controller('myController', function ($scope, $compile) {
$scope.html ='<div><button ng-click="callMe()">clickme</button><div>';
});