我在app.js中定义了不同的 Controller 和相应的模板url:
var App = angular.module('FormApp', [ 'ngRoute','ui.bootstrap', 'dialogs', 'oc.modal' ]);
App.config([ '$routeProvider', function($routeProvider) {
$routeProvider.when('/addClient', {
templateUrl : '../../resources/partialHtml/addClientLayout.html',
controller : FormController
}).when('/conflist/:commandName/:client/:env', {
templateUrl : '../../resources/partialHtml/testPrase.html',
controller : TestParseController
}).when('/addNewCommand', {
templateUrl : '../../resources/partialHtml/addNewCommand.html',
controller : AddNewCommandController
})
} ]);
我的 TestParseController 的定义如下:
var TestParseController = function($scope, $window, $http, $routeParams, $sce,
$compile) {
$scope.hide = function(obj) {
alert($routeParams.commandName);
};
$scope.to_trusted1 = function(html_code) {
html_code = $sce.trustAsHtml(html_code);
$scope.content = html_code;
alert(html_code);
$compile( document.getElementById('innerh'))($scope);
};
$http.get('client/getConfList/' + $routeParams.commandName)
.success(
function(data) {
$scope.html_content = "<button data-ng-click='hide($event)'>Click me!</button>";
$scope.to_trusted1($scope.html_content);
});
}
Html:testParse.html:
<h3 data-ng-click="hide($event)" class="plus">Add</h3>
<div ng-bind-html="content" id="innerh"> </div>
div 已正确填充,但填充按钮的 ng-click 不起作用,但它适用于页面本身可用的 h3 标记。
请有人帮忙..
最佳答案
使用以下内容而不是 $scope.content
更改填充 innerh div 的方式(并从内部 div 中删除 ng-bind-html
):
document.getElementById('innerh').innerHTML = html_code;
进入to_trusted1
功能:
$scope.to_trusted1 = function(html_code) {
html_code = $sce.trustAsHtml(html_code);
$scope.content = html_code;
//alert(html_code);
document.getElementById('innerh').innerHTML = html_code;
};
jsfiddle:https://jsfiddle.net/m37xksxk/
解决方案 2:
更 AngularJS 的方式可能是使用 $timeout
.
您可以使用它来确保内容包含在 div 内。您还必须获取 div 内部的内容,因为这就是要编译的内容: angular.element(document.getElementById('innerh')).contents()
:
所以它会变成:
$timeout( function(){
$compile( angular.element(document.getElementById('innerh')).contents())
($scope);
}, 0);
jsfiddle 2:https://jsfiddle.net/m37xksxk/1/
关于angularjs - 无法在 angularjs Controller 中点击 ng-click?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29302952/