angularjs - 无法在 angularjs Controller 中点击 ng-click?

标签 angularjs angularjs-ng-click ng-bind-html

我在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/

相关文章:

javascript - AngularJS 中的循环编号验证

javascript - 在我的情况下如何返回对象?

angularjs ng-click 默默地吃错误

angularjs - 在AngularJS中将iframe动态插入页面

javascript - 如何将 ng-click 绑定(bind)到插入指令嵌入 HTML block 内的 HTML block

javascript - Node.js 和 Angular.js

javascript - 单独的 Controller AngularJS

angularjs - 如何在angularjs中检索点击的ElementId?

javascript - 在 ng-click 函数中恢复 Angular 对象值

javascript - ng-bind-html 不适用于输入标签