Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 最近创建的元素不调用ng click_Javascript_Angularjs - Fatal编程技术网

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

Javascript 最近创建的元素不调用ng click,javascript,angularjs,Javascript,Angularjs,我的代码中有一些html元素,稍后会添加到页面上。但是,当您稍后添加它时,指令ng click不起作用 我尝试过的另一个解决方案是使用onclick属性在这个后来添加的元素上调用node方法,但这意味着在控制器之外调用angularJs方法是不可能的(如果是这样,对于许多类型的问题可能是一个很好的解决方案) 下面是JSFIDLE示例: 以下是标记: <div ng-app="myApp" ng-controller="MyController" > <button type=

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

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

下面是JSFIDLE示例:

以下是标记:

<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>' ;
    }

});
var myApp=angular.module('myApp',[]);
函数另一条路径(){
警报(“另一种方法是在外部调用节点方法,但如何执行?”)
//哦,伙计,我在这里要写什么?
//myApp.controller.scope()……我真的不知道
}
myApp.controller('MyController',函数($scope){
$scope.testFunction=函数(a){
警报(a)
}
$scope.addElement=函数(){
document.getElementById('foodiv').innerHTML='STEP 3.这不起作用';
}
});

谢谢你

看来你在以一种“无角度”的方式做事

首先,这种情况发生在您身上,因为您是在angular将
$compile
d添加到视图之后添加这些元素的

“角度方式”的一种方法是对按钮使用
ng show
/
ng hide
指令,并使用控制器显示/隐藏它们

另一种方法是这样做:

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

以及使用控制器向该阵列添加按钮。然后使用
ng repeat

在视图中呈现此数组,请参阅关于
$compile
服务。但是不管怎样,如果您在angular controller中使用dom,您会犯一些错误,请尝试查看为什么要在稍后的页面上添加元素?也许有一种更惯用的方式来实现你想要实现的目标。为什么不考虑SPA,它会在步骤转换时改变html谢谢大家,我读得更多一些,想得更多一些。。。