2016-06-23 70 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>

相关问题