AngularJS - ngClick not working on dynamically added html

白昼怎懂夜的黑 提交于 2019-12-12 01:38:40

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/23762376/angularjs-ngclick-not-working-on-dynamically-added-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!