更新输入值正在更新angularJS

时间:2016-08-08 06:23:21

标签: javascript angularjs

这是我的JS代码。

angular.module('myApp', [])
.controller("myController", [function () {
    this.master = [];

    this.addUser = function(user) {
                this.master.push(user)
    };

    this.removeUser = function(user) {
        var indexToRemove = this.master.indexOf(user);
        this.master.splice(indexToRemove,1)
    }

    this.reset = function() {
        this.user = this.master[this.master.length - 1];
    }

}])

这是我的HTML部分。

<body ng-app="myApp" ng-controller="myController as Cntrl">
    <form>
        Name: <input type="text" ng-model="user.name" /> <br />
        Email: <input type="email" ng-model="user.email" /> <br />
        Gender: <input type="radio" ng-model="user.gender" value="male" /> Male
        <input type="radio" ng-model="user.gender" value="female" /> female <br /> <br />

        <input type="button" ng-click="Cntrl.addUser(user)" value="Add User">  

        <input type="button" ng-click="Cntrl.reset()" value="Reset User"> 

    </form>

    <div ng-repeat="users in Cntrl.master track by $index">
         <span ng-click="Cntrl.removeUser(users)" >X</span> <pre>{{users | json}}</pre>

    </div>

</body>

我可以添加新用户并删除所选用户。但每当我添加任何新用户时,阵列中所有旧用户的属性都会使用新添加的用户的属性进行更新。

请解释我在这里犯的错误。

3 个答案:

答案 0 :(得分:0)

推入阵列的所有用户都是同一个,并删除更好的使用索引,          纳克单击=&#34; Cntrl.removeUser($指数)&#34;

&#13;
&#13;
angular.module('myApp', [])
  .controller("myController", [
    function() {
      this.master = [];
      this.user = this;

      //use this.user
      this.addUser = function() {
        this.master.push(this.user)
        this.user = {}
      };

      //use index
      this.removeUser = function(index) {
        this.master.splice(indexToRemove, 1)
      }

      this.reset = function() {
        this.user = this.master[this.master.length - 1];
      }

    }
  ])
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您正在向用户提供对master数组的引用,并且由于双向数据绑定您的值已更新,您可以尝试这样做,也可以。

只需修改你的addUser方法,如下所示。

     this.addUser = function(user) {
        this.master.push(angular.copy(user));
    };

角度副本将创建对象的深层副本,请参阅文档https://docs.angularjs.org/api/ng/function/angular.copy

答案 2 :(得分:0)

  

由于已有3篇文章回答了您的问题。但是我   猜测虚拟机存在一些严重的逻辑误解   你试图在你的代码中实现的方法。虽然是程序   现在正在工作,但我强烈建议你通过约翰   在继续您的解决方案之前,Papa的教程。这很清楚   你的基础知识,让你明白为什么它不起作用   之前。

https://johnpapa.net/angularjss-controller-as-and-the-vm-variable/