Programing

AngularJS 지시문 : UI에 반영되지 않은 $ scope 변경

lottogame 2020. 12. 10. 08:24
반응형

AngularJS 지시문 : UI에 반영되지 않은 $ scope 변경


AngularJS로 사용자 지정 요소를 만들고 일부 이벤트를 바인딩하려고하는데, 바인딩 함수에서 사용할 때 $ scope.var가 UI를 업데이트하지 않는 것을 알았습니다.

다음은 probelm을 설명하는 간단한 예입니다.

HTML :

<!doctype html>
<html ng-app="test">
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
    <script src="script.js"></script>

  </head>
  <body>

<div ng-controller="Ctrl2">
  <span>{{result}}</span>
  <br />
  <button ng-click="a()">A</button>
  <button my-button>B</button>

</div>


  </body>
</html>

JS :

function Ctrl2($scope) {
    $scope.result = 'Click Button to change this string';
    $scope.a = function (e) {
        $scope.result = 'A';
    }
    $scope.b = function (e) {
        $scope.result = 'B';
    }
}

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

mod.directive('myButton', function () {
    return function (scope, element, attrs) {
        //change scope.result from here works
        //But not in bind functions
        //scope.result = 'B';
        element.bind('click', scope.b);
    }
});

데모 : http://plnkr.co/edit/g3S56xez6Q90mjbFogkL?p=preview

기본적으로 click이벤트를 바인딩 my-button하고 $scope.result사용자가 버튼 B를 클릭했을 때 변경하고 싶습니다 ( ng-click:a()버튼 A 와 유사 ). 하지만 이렇게하면 뷰가 새 뷰로 업데이트되지 않습니다 $scope.result.

내가 뭘 잘못 했어? 감사.


이벤트 핸들러를 "외부"Angular라고합니다. 따라서 $scope속성이 업데이트 되더라도 Angular는 이러한 변경 사항을 알지 못하기 때문에 뷰가 업데이트되지 않습니다.

$scope.$apply()이벤트 핸들러 하단에서 호출 하십시오. 이로 인해 다이제스트 사이클 이 실행되고 Angular는 $scope( HTML에서 $watches사용하여 설정 한 Angular로 인해) 변경 사항을 {{ ... }}확인하고 뷰를 업데이트합니다.


이것은 또한 다른 문제의 결과 일 수 있지만 증상은 동일합니다.

뷰에 할당 된 상위 범위를 삭제하면 해당 변경 사항이 $apply()호출 후에도 뷰에 영향을주지 않습니다 . 예제 보기 -텍스트 입력을 통해보기 값을 변경할 수 있지만을 클릭 Destroy parent scope!하면 모델이 더 이상 업데이트되지 않습니다.

나는 이것을 버그로 생각하지 않습니다. 오히려 응용 프로그램의 너무 해키 코드의 결과입니다 :-)

I faced this problem when using Angular Bootstrap's modal. I tried to open second modal with scope of the first one. Then, I immediately closed the first modal which caused the parent scope to be destroyed.


use timeout

$timeout(function () { code.... }, 0);

참고URL : https://stackoverflow.com/questions/16066170/angularjs-directives-change-scope-not-reflected-in-ui

반응형