ngrepeat在angularJS中的奇怪行为

时间:2017-03-03 14:55:07

标签: angularjs

我遇到问题ng-repeat,它用最新的值替换所有值。

E.g。我正在向文本框添加一个值,然后在ng-repeat div中添加该值,但是它将所有值替换为输入的最后一个值。

这是Jsfiddle

https://jsfiddle.net/mahajan344/9bz4Lwxa/656/

1 个答案:

答案 0 :(得分:1)

这种情况正在发生,因为您只有一个statusObj并且每次有人点击“添加新状态”按钮时您都会对其进行修改。删除您现在拥有的statusObj,并让AddNewStatus方法每次都创建一个新方法:

var xyzApi = xyzApi || {
  sayHello: function() {
    return "hey there\n";
  }
};

angular.module('demoApp', [])
  .controller('MainController', MainController)
  .provider('xyzApi', function XyzApiProvider() {

    this.$get = function() {

      var xyzApiFactory = {
        otherFunction: function() {
          //$log.log('other function called');
          return 'other function \n';
        }
      };
      //console.log(xyzApiFactory, xyzApi);
      angular.merge(xyzApiFactory, xyzApi);
      return xyzApiFactory;
    };
  });


function MainController(xyzApi) {
  var vm = this;
  vm.test = '';
  vm.listOfStatus = [];
  vm.showStatusError = false;
  vm.statusText = "";

  vm.sayHello = function() {
    vm.test += xyzApi.sayHello() + xyzApi.otherFunction();
  }

  vm.AddNewStatus = function(statusText) {
    if (statusText.length < 1) {
      vm.showStatusError = true;
      return;
    } else {
      vm.showStatusError = false;
    }

    var statusObj = {
      StatusComment: statusText,
      scId: 0,
      scTimeStamp: new Date(),
      JobNum: 0,
      IsNew: 0,
    };

    vm.listOfStatus.push(statusObj);
    vm.statusText = "";
  };

  vm.RemoveStatus = function(index) {

    vm.listOfStatus.splice(index, 1);

  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-rc.0/angular.js"></script>
<div ng-app="demoApp" ng-controller="MainController as mainCtrl">
  <pre>{{mainCtrl.test}}</pre>
  <button ng-click="mainCtrl.sayHello()">
    say hello!!
  </button>

  <div id="DivStatus">
    <div class="form-group">
      Status
      <div class="col-md-3 col-sm-3 col-xs-12">
        <input type="text" ng-model="mainCtrl.statusText" id="txtStatus" class="form-control col-md-7 col-xs-12">
        <div class="text-danger error-message" id="txtStatusError" ng-show="showStatusError">Please enter new status</div>
      </div>
      <div class="col-md-3 col-md-3x col-sm-3 col-xs-12">
        <input type="button" class="btn" ng-click="mainCtrl.AddNewStatus(mainCtrl.statusText)" value="Add New Status" />
      </div>
    </div>
    <div class="form-group" ng-repeat="statusObj in mainCtrl.listOfStatus track by $index">

      <div class="col-md-3 col-sm-3 col-xs-12">
        <input type="text" value="{{statusObj.StatusComment}}" ng-disabled="true" class="form-control col-md-7 col-xs-12">
      </div>
      <span class="remove-record" ng-click="mainCtrl.RemoveStatus($index)" style="cursor:pointer"><i class="fa fa-times"></i></span>

    </div>
  </div>
</div>