AngularJS - ngClick 不适用于动态添加的 html [英] AngularJS - ngClick not working on dynamically added html

查看:22
本文介绍了AngularJS - ngClick 不适用于动态添加的 html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的应用程序,其中有一个带有 mylist 模型的输入元素.如果 mylist=1 ng-include first.html,如果 mylist=2 ng-include second.html.到现在为止还挺好.

我的问题是,在每个 html 模板中,我都有一个按钮,单击该按钮时我想更改 mylist 的值,以便我可以导航到另一个模板,为了实现这一点,我这样做:

<button ng-click="mylist=x" >切换到 x</button>

但 ng-click 不起作用.为什么?

这是我的代码:

scripts.js

var myApp = angular.module('myApp', []);myApp.controller('MainController', function ($scope) {$scope.mylist = 1;});

index.html

<html ng-app="myApp"><头><script src="https://code.angularjs.org/1.2.16/angular.js"></script><script src="script.js"></script><body ng-controller="MainController"><input type="number" ng-model="mylist"/>{{mylist}}<br/><div ng-switch on="mylist"><div ng-switch-when=1><ng-include src="'first.html'"></ng-include>

<div ng-switch-when=2><ng-include src="'second.html'"></ng-include>

first.html

first

<button ng-click="mylist=2" >切换到 2</button>

second.html

<button ng-click="mylist=1">切换到 1</button>

这里还有 Plunker http://plnkr.co/edit/bVATLV66kN21LC8EPeoW

解决方案

ng-include 创建一个 子范围.所以你应该绑定到一个对象属性而不是一个基元.

$scope.my = {清单:1};

http://plnkr.co/edit/SbeGch5MJdux33HgYsEJ?p=preview

I have a simple app in which i have a single input element with a mylist model. If mylist=1 i ng-include first.html and if mylist=2 i ng-include second.html. So far so good.

My problem is that in each html template i have a button that when clicked i want to change the value of mylist so i can navigate to the other and in order to achieve this i do:

<button ng-click="mylist=x" >switch to x</button>

but ng-click doesn't work. Why?

Here is my code:

scripts.js

var myApp = angular.module('myApp', []);

myApp.controller('MainController',  function ($scope) {

    $scope.mylist = 1;

});

index.html

<!DOCTYPE html>
<html ng-app="myApp">

<head>
  <script src="https://code.angularjs.org/1.2.16/angular.js"></script>
  <script src="script.js"></script>
</head>

<body ng-controller="MainController">
  <input type="number" ng-model="mylist" />{{mylist}}
  <br/>
  <div ng-switch on="mylist">

    <div ng-switch-when=1>
      <ng-include src="'first.html'"></ng-include>
    </div>
    <div ng-switch-when=2>
      <ng-include src="'second.html'"></ng-include>
    </div>
  </div>
</body>

</html>

first.html

<p>first</p>
<button ng-click="mylist=2" >switch to 2</button>

second.html

<p>second</p>
<button ng-click="mylist=1">switch to 1</button>

Also here is the Plunker http://plnkr.co/edit/bVATLV66kN21LC8EPeoW

解决方案

ng-include creates a child scope. So you should bind to an object property instead of a primitive.

$scope.my = {
  list: 1
};

http://plnkr.co/edit/SbeGch5MJdux33HgYsEJ?p=preview

这篇关于AngularJS - ngClick 不适用于动态添加的 html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆