首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用$index ()获取ngrepeat $index

使用$index ()获取ngrepeat $index
EN

Stack Overflow用户
提问于 2016-06-23 13:58:21
回答 1查看 777关注 0票数 0

我对AngularJs很陌生,我很好奇在输入中获取ngrepeat索引的最佳方法是什么,并比较新字符串是否与原始值不同:

联署材料:

代码语言:javascript
复制
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:

代码语言:javascript
复制
  <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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-06-23 14:21:58

您可以使用数据保存初始值,然后比较更改的值。您可以在纯angularjs结构中这样做,而无需使用document.getElementById和其他哈克:

代码语言:javascript
复制
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";
    };
  });
代码语言:javascript
复制
<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> 

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37993798

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档