最近创建的元素不会调用 ng-click

Lately created elements does not call ng-click

本文关键字:调用 ng-click 元素 创建 最近      更新时间:2023-09-26

我的代码中有一些稍后在页面上添加的html元素。 但是当你稍后添加它时,指令ng-click不起作用。

我尝试过的另一个解决方案是使用 onclick 属性在这个后来添加的元素上调用节点方法,但这意味着在控制器外部调用 angularJs 方法,这是不可能的(如果是这样,可能是许多类型问题的好解决方案)

下面是 JSFIDDLE 示例:http://jsfiddle.net/hugoofab/wktqrhv3/1/

下面是标记:

<div ng-app="myApp" ng-controller="MyController" >
<button type="button" ng-click="testFunction('this will work')">STEP 1. this will work</button>
<button type="button" ng-click="addElement()" >STEP 2. add button</button>
    <div id="foodiv"></div>
<button type="button" onclick="anotherWay()" >STEP 4. another way</button>

这是javascript:

var myApp = angular.module('myApp', []);
function anotherWay ( ) {
    alert("another way would be call node method outside, but how to do it?")
    // ohhh man.. what I'll code here?
    //myApp.controller.scope()..... I really don't know
}
myApp.controller('MyController', function($scope) {
    $scope.testFunction = function ( a ) {
        alert(a)
    }
    $scope.addElement = function ( ) {
        document.getElementById('foodiv').innerHTML = '<button type="button" ng-click="testFunction(''this will not work'')">STEP 3. this will not work</button>' ;
    }
});

谢谢!

你似乎在以"非角度"的方式做事......

首先,这发生在你身上,因为你在 angular $compile视图之后添加了这些元素。

"角度方式"的一种方法是在按钮上使用ng-show/ng-hide指令,并使用控制器显示/隐藏它们。

另一种方法是有这样的东西:

$scope.buttons = [{ }, { }];

并使用控制器向此数组添加按钮。然后使用 ng-repeat 在视图中呈现此数组。