programing

angularjs - ngRepeat with ngInit - ngRepeat는 렌더링된 값을 새로 고치지 않습니다.

css3 2023. 10. 12. 23:26

angularjs - ngRepeat with ngInit - ngRepeat는 렌더링된 값을 새로 고치지 않습니다.

저는 ngRepeater를 사용하여 표시되는 배열을 가지고 있지만, 이 지시를 사용하여 표시할 객체를 반환해야 하는 함수를 실행하는 ngInit 지시를 사용하고 있습니다.모든 것이 완벽하게 작동하지만 배열에 새 값을 추가하는 "새" 버튼을 추가하면 배열 값의 양에 따라 기능이 실행되어야 한다고 생각되는 "SetPreview" 기능이 실행됩니다.내가 어떻게 그럴 수 있을까?

UI:

<body ng-app>

  <ul ng-controller="PhoneListCtrl">
      <button ng-click="add()">Add</button>
    <li ng-repeat="phone in phones" ng-init="displayedQuestion=SetPreview(phone);">
      {{displayedQuestion.name}}
      <p>{{displayedQuestion.snippet}}</p>
    </li>
  </ul>
</body>

컨트롤러:

function PhoneListCtrl($scope) {
  $scope.phones = [
    {"name": "Nexus S",
     "snippet": "Fast just got faster with Nexus S."},
    {"name": "Motorola XOOM™ with Wi-Fi",
     "snippet": "The Next, Next Generation tablet."},
    {"name": "MOTOROLA XOOM™",
     "snippet": "The Next, Next Generation tablet."}
  ];

    $scope.add = function(){
        this.phones.push({name:'1', snippet:'n'});
    };        
    $scope.SetPreview = function(phone)
    {
        //here logic which can take object from diffrent location
        console.log(phone);
        return phone;
    };
}

샘플이 여기 있습니다 - jsfiddle

편집:
여기 더 복잡한 샘플이 있습니다. -> 이제 전화 모음이 비어 있습니다. 추가 버튼을 클릭하면 새 항목이 추가되어 편집 가능(텍스트 필드에서 값을 변경할 수 있음)으로 설정되고 ngRender가 실행되면 편집 가능한 개체가 반환됩니다(미리보기와 같은 작업입니다).이제 Add 버튼을 다시 클릭해 보십시오. 첫 번째 항목의 편집 가능한 값이 여전히 사용자에게 제공되지만 ng-repeater 전체를 새로 고치고 싶습니다.

각도 성능 기능을 실행하고 있습니다.

기본적으로 Angular는 배열의 요소(예: A')가 동일한 객체 참조이므로 ng-init를 다시 호출하지 않습니다.이게 효율적입니다.이전 목록을 새 목록에 연결해도 Angular는 동일한 참조를 확인할 수 있습니다.

대신 이전 개체와 동일한 값을 가진 새 개체를 생성하면 다른 참조가 발생하고 Angular re-init: http://jsfiddle.net/fqnKt/37/ 을 다시 시작합니다.

$scope.add = function(item) {
    var newItems = [];
    angular.forEach($scope.items, function(obj){
        this.push({val:obj.val});
    },newItems)

    newItems.push({val:item})
    $scope.items = newItems;
};

fiddle에서 사용하는 접근 방식을 추천하지는 않지만, 코드를 트리거하려면 ng-init와는 다른 방법을 찾아야 합니다.

대체할 수 있다는 걸 알게 됐어요ng-init각 잡힌 표정으로{{}}숨겨진 블록에서:

<body ng-app>

<ul ng-controller="PhoneListCtrl">
    <button ng-click="add()">Add</button>
    <li ng-repeat="phone in phones">
      <span style="display: none">{{displayedQuestion=SetPreview(phone)}}</span>
      {{displayedQuestion.name}}
      <p>{{displayedQuestion.snippet}}</p>
    </li>
  </ul>
</body>

요소에 ngInit이 있고 하위 요소에 ngRepeat이 있는 경우 ngInit은 한 번만 실행됩니다.

이를 해결하려면 ngInit을 사용하여 요소에 ngRepeat을 추가합니다. 한 번 반복되며 동일한 배열(및 기타 종속성)에 종속되는 식을 사용합니다.

예를 들어,

ng-repeat="_ in [ products ]" ng-init="total = 0"

언급URL : https://stackoverflow.com/questions/15355122/angularjs-ngrepeat-with-nginit-ngrepeat-doesnt-refresh-rendered-value