programing

angular.js를 사용하여 모델 재설정

fastcode 2023. 3. 26. 11:52
반응형

angular.js를 사용하여 모델 재설정

단순히 다음과 같이 값을 리셋하려고 합니다.

$scope.initial = [
    {
        data1: 10,
        data2: 20
    }            
];


$scope.datas= $scope.initial;


$scope.reset = function(){
  $scope.datas = $scope.initial;  
}

하지만 아무것도 만들어내지 않아요 고칠 생각은 없나요?

angular.module('app', []).controller('MyCtrl', function($scope) {
  $scope.initial = [
    {
      data1: 10,
      data2: 20
    }            
  ];

  $scope.datas= $scope.initial;

  $scope.reset = function(){
    $scope.datas = $scope.initial;  
  } 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MyCtrl">
  <div ng-repeat="data in datas">
    <input type="text" ng-model="data.data1" />
    <input type="text" ng-model="data.data2" />
  </div>
  <a ng-click="reset()">Reset to initial value</a>
  or     
  <button ng-click="name = initial">Reset to initial value</button>
  <hr />
  <p ng-repeat="data in datas">{{data.data1}}, {{data.data2}}</p>
</div>

jsfiddle에 대한 작업 예가 있습니다.

JavaScript에 대한 질문입니다(그래서 "javascript" 태그를 추가했습니다).JavaScript 객체(배열 $scope 등)의 경우.initial)은 변수에 할당되며, 변수는 복사가 아닌 참조에 의해 할당됩니다.그래서 이 문장은

$scope.datas= $scope.initial;

$126.19달러가 $194를 가리키게 됩니다.첫 번째 오브젝트$scope.datas 또는 $scope에 대한 변경.initial은 모두 같은(단일) 오브젝트에 영향을 줍니다.ng-model은 오브젝트 요소 data1과 data2를 데이터 바인딩하는데 사용되므로 텍스트 입력을 변경하면 $scope.datas가 참조하는 오브젝트의 data1과 data2 요소(예: $scope)가 변경됩니다.초기의.동작하고 있는 것을 확인하려면 , 다음의 항목을 바이올린의 HTML 에 추가합니다.

<p>{{initial}}</p>

텍스트 상자에서 값을 변경하면 $scope가 표시됩니다.initial도 변경됩니다.

@Max는 리셋 함수로 use angular.copy()라는 부분적인 답변을 제공했습니다.단, 초기 할당에서도 angular.copy()를 사용해야 합니다.

 $scope.datas = angular.copy($scope.initial);

업데이트:

@EpokK가 그의 답변에 나타나 있듯이 대체 솔루션은 다음과 같습니다.

angular.copy($scope.initial, $scope.datas);

@bekite가 답변에서 언급했듯이 @EpokK의 솔루션은 다른 개체를 생성하지 않습니다.

풀코드

angular.module('app', []).controller('MyCtrl', function($scope) {
  $scope.initial = [{
    data1: 10,
    data2: 20
  }];
  $scope.datas = angular.copy($scope.initial);
  $scope.reset = function () {
    $scope.datas = angular.copy($scope.initial);
    // or
    // angular.copy($scope.initial, $scope.datas);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="MyCtrl">
  <div ng-repeat="data in datas">
    <input type="text" ng-model="data.data1" />
    <input type="text" ng-model="data.data2" />
  </div> 
  <a ng-click="reset()">Reset to initial value</a>
  or
  <hr />
  <p ng-repeat="data in datas">{{data.data1}}, {{data.data2}}</p>{{initial}}
</div>

fiddle

를 변경해 보겠습니다.reset사용하는 기능

$scope.reset = function () {
    $scope.datas = angular.copy($scope.initial);
};

@Mark Rajcok:오해는 하지 마세요. 하지만 저는 그렇게 생각해요.

angular.copy($scope.initial, $scope.datas);

는 의 대체 구문이 아닙니다.

$scope.datas = angular.copy($scope.initial);

내가 이해하는 방식:

$scope.datas = angular.copy($scope.initial);

$scope 복사본을 만듭니다.initial을 지정하면 참조가 $180.disc.disc에 할당됩니다.

angular.copy($scope.initial, $scope.datas);

$scope.datas 값을 $scope로 업데이트합니다.초기값

return 스테이트먼트에 대한 자세한 내용은 angularjs documents(http://docs.angularjs.org/api/angular.copy )를 참조해 주세요.

대상이 지정된 경우 복사 또는 업데이트된 대상을 반환합니다.

동작 구문:

$scope.reset = function () {
    angular.copy($scope.initial, $scope.datas);
};

API 레퍼런스:angular.copy(source[, destination]);

다음 버튼을 고려하십시오.

  • 편집
  • 절약하다
  • 취소

사용자가 [편집]을 클릭하여 데이터를 변경한 후 [취소]버튼을 사용하여 오래된 데이터를 취득하면 다음과 같이 구현할 수 있습니다.

HTML

<div>
    <button data-ng-click="edit()" data-ng-show="!editing">Edit</button>
    <button data-ng-click="save()" data-ng-show="editing">Save</button>
    <button data-ng-click="cancel()" data-ng-show="editing">Cancel</button>
</div>

각도 JS

$scope.edit = function () {
    $scope.editing = true;
    $scope.copy = angular.copy($scope.data);
};

$scope.cancel = function () {
    $scope.editing = false;
    $scope.data = $scope.copy;
};

레퍼런스

나는 Yasser의 코멘트가 좋다: 명확하고 간결하다.

편집을 시작할 때 값을 복사하고 취소/저장 시 참조를 대체하는 것이 좋습니다.

원본 데이터가 아닌 로컬 복사본에 바인딩한 다음 저장 시에만 최종 데이터를 변경하는 것이 좋습니다.이렇게 하면 나중에 모든 종류의 버그가 방지되고 편집 동작이 캡슐화됩니다.

최종 버전은 다음과 같습니다.

function initValue() {
    $scope.bound = angular.copy($scope.data);
}

function setValue() {
    $scope.data = $scope.bound;
}

$scope.edit = function () {
    $scope.editing = true;
    initValue();
};

$scope.cancel = function () {
    $scope.editing = false;
    initValue();
};

$scope.save= function () {
    $scope.editing = false;
    setValue();
};

위에서 말한 대로 백업을 유지하며 사용했지만 사용 중 문제가 하나 더 발생했습니다.
에 이 될 것

프로필 섹션 코드는 다음과 같습니다.

var profileBackup ={};
$scope.profileContinue = function()
{
  profileBackup = angular.copy($scope.userData.profile); 
//  profileBackup = $scope.userData.profile; 
//other code
}

$scope.profileCancel = function()
{
$scope.userData.profile = profileBackup;
}

그런데 모델 변경 시 범위 외 변수 프로파일 백업도 업데이트되는 것을 보고 놀랐습니다(이 경우 참조가 반환됩니다).

그리고 코드를 이렇게 바꿨습니다.

$scope.profileContinue = function()
{
  profileBackup = angular.toJson($scope.userData.profile); 
//  profileBackup = $scope.userData.profile; 
//other code
}

$scope.profileCancel = function()
{
$scope.userData.profile = angular.fromJson(profileBackup);
}

말이 안 된다고 해도 용서해 주세요

언급URL : https://stackoverflow.com/questions/13085024/reset-a-model-with-angular-js

반응형