ProgramingTip

모델 변경시 AngularJS 뷰가 업데이트되지 않음

bestdevel 2020. 10. 28. 20:21
반응형

모델 변경시 AngularJS 뷰가 업데이트되지 않음


Angular가 어떻게 작동하는지 알아 내려고하는데 모델이 변경 될 때 뷰를 업데이트하는 데 문제가 있습니다.

HTML

<div ng-app="test">  
        <p ng-controller="TestCtrl">  
            {{testValue}}  
        </p>  
    </div>

JS

var app = angular.module('test', []);

    app.controller('TestCtrl', function ($scope) {
       $scope.testValue = 0;

        setInterval(function() {
            console.log($scope.testValue++);
        }, 500);
    });

http://jsfiddle.net/N2G7z/

어떤 아이디어?


Ajay beniwal이 언급했듯이 소화를 시작하기 위해 적용합니다.

var app = angular.module('test', []);

app.controller('TestCtrl', function ($scope) {
   $scope.testValue = 0;

    setInterval(function() {
        console.log($scope.testValue++);
        $scope.$apply() 
    }, 500);
});

$ interval을 사용하십시오.

다음은 수정 된 코드입니다. http://plnkr.co/edit/m7psQ5rwx4w1yAwAFdyr?p=preview

var app = angular.module('test', []);

app.controller('TestCtrl', function ($scope, $interval) {
   $scope.testValue = 0;

    $interval(function() {
        $scope.testValue++;
    }, 500);
});

setTimout각도 밖에서 실행됩니다. $timeout이 작업을 수행 할 서비스 를 사용 합니다.

var app = angular.module('test', []);

    app.controller('TestCtrl', function ($scope, $timeout) {
       $scope.testValue = 0;

        $timeout(function() {
            console.log($scope.testValue++);
        }, 500);
    });

그 이유는 앵귤러의 양방향 바인딩이 더티 검사를 사용하기 때문입니다. 글은 앵귤러의 더티 검사에 대해 읽어보기에 좋은 가이드 입니다. 사이클을 $scope.$apply()시작 $digest합니다. 바인딩이 적용됩니다. $timeout처리하는 $apply당신을 위해 시간 제한을 사용할 때 사용하는 추천 서비스가 그래서.

기본적으로 바인딩은 $digest주기 중에 발생 합니다 (값이 다른 것으로 보이는 경우).


$scope.$apply()각도를 사용하지 마십시오. 이미 사용하고 있으며이 오류가 발생할 수 있습니다.

$ rootScope : inprog 작업이 이미 진행 중입니다.

두 번 사용하는 경우 사용 $timeout또는 간격

참고 URL : https://stackoverflow.com/questions/20070077/angularjs-view-not-updating-on-model-change

반응형