使用getElementById()获取ngrepeat $ index

时间:2016-06-23 13:58:21

标签: javascript angularjs

我是AngularJs的新手,我很想知道在输入上获取ngrepeat索引的最佳方法是什么,并比较新字符串是否与原始值不同:

JS:

var checkIfDataSampleHasChanged = document.getElementById('dsField' + i).value;
     console.log(checkIfDataSampleHasChanged);
     console.log($scope.currentSchema)
     if (checkIfDataSampleHasChanged != $scope.currentSchema.sDataSamples.dsName) {
       console.log("hello there")
       $scope.currentSchema.sDataSamples.dsName = checkIfDataSampleHasChanged;
     }

HTML:

  <fieldset ng-repeat="ds in currentSchema.sDataSamples track by $index">
  <label for="{{dsField$index}}" style="width:400px;">
    Data Sample Name ({{ds.dsFileName}}):</label>
  <input name="{{dsField$index}}" type="text" style="width: 400px;" ng-model="currentSchema.sDataSamples[$index].dsName" value="{{ds.dsName}}" />
  <br>
  <br>
</fieldset>

1 个答案:

答案 0 :(得分:2)

您可以使用数据保存初始值,然后比较更改后的值。您可以在纯angularjs构造中执行此操作,而无需使用document.getElementById和其他黑客:

angular
  .module('app', [])
  .controller('AppController', function ($scope) {
  var initialSample = [
      {id: 1, name: 'Abc'},
      {id: 2, name: 'def'},
      {id: 3, name: 'ghi'},
      {id: 4, name: 'jkl'},
      {id: 5, name: 'mno'}
  ];
    $scope.sample = angular.merge([], initialSample);
  
    $scope.checkIfValueChanged = function ($index) {
      var isValChanged = initialSample[$index].name !== $scope.sample[$index].name;
      console.log(isValChanged);
      if (isValChanged) {
        alert("Value has changed");
      } else {
        alert("Value has not changed");
      }
    };
  
    $scope.changeVal = function(){
      var randInt = Math.floor(Math.random() * 5);
      console.log(randInt);
      $scope.sample[randInt].name = "Lorem ipsum";
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<div ng-app='app' ng-controller='AppController'>
    <ul>
      <li ng-repeat="item in sample" ng-click="checkIfValueChanged($index)">
        {{item.name}}
      </li>
    </ul>
    
    <button ng-click="changeVal()"> Change random value </button>
  </div>