AngularJS - ngClick not working on dynamically add

2019-09-01 04:27发布

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条回答
孤傲高冷的网名
2楼-- · 2019-09-01 05:18

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

查看更多
登录 后发表回答