2016-06-23 106 views
0

我是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> 
+0

我想這是一個形式,並且要對所有上提交的投入運行此。既然如此,您可以將表單作爲參數傳遞給提交函數,並且可以單獨訪問其所有成員,並將它們與其原始數據對應進行比較。 – CautemocSg

回答

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>

相關問題