programing

파라미터 변경 시 Angular Directive 새로 고침

newnotes 2023. 3. 31. 22:37
반응형

파라미터 변경 시 Angular Directive 새로 고침

다음과 같이 초기화되는 각도 지시어가 있습니다.

<conversation style="height:300px" type="convo" type-id="{{some_prop}}"></conversation>

지시사항을 갱신할 수 있도록 스마트하게 하고 싶다.$scope.some_prop완전히 다른 내용을 표시해야 한다는 것을 의미합니다.

그대로 테스트했지만 아무 일도 일어나지 않습니다.링크 기능이 호출되지도 않습니다.$scope.some_prop변화들.이런 일이 일어나게 할 방법이 있을까요?

링크 함수는 한 번만 호출되므로 원하는 대로 직접 수행되지 않습니다.앵귤러를 사용해야 합니다.$watch모델 변수를 확인합니다.

이 시계는 링크 기능으로 설정해야 합니다.

디렉티브에 격리된 스코프를 사용하는 경우 스코프는 다음과 같습니다.

scope :{typeId:'@' }

링크 기능에서 다음과 같은 시계를 추가합니다.

link: function(scope, element, attrs) {
    scope.$watch("typeId",function(newValue,oldValue) {
        //This gets called when data changes.
    });
 }

격리된 스코프를 사용하지 않는 경우 watch on을 사용하십시오.some_prop

이 경우 디렉티브 속성의 속성을 감시할 수 있습니다.다음과 같이 $observe()를 사용하여 속성 변경 속성을 확인할 수 있습니다.

angular.module('myApp').directive('conversation', function() {
  return {
    restrict: 'E',
    replace: true,
    compile: function(tElement, attr) {
      attr.$observe('typeId', function(data) {
            console.log("Updated data ", data);
      }, true);

    }
  };
});

모델 사용 여부와 성능에 민감한지 여부에 대해 언급하지 않았기 때문에 이 지침에서 '컴파일' 함수를 사용했습니다.

모델이 있는 경우 컴파일 함수를 '링크'로 변경하거나 '컨트롤러'를 사용해야 합니다.모델의 변경 속성을 감시하려면 $watch()를 사용하여 속성에서 각 {{}}개의 괄호를 선택해야 합니다.예:

<conversation style="height:300px" type="convo" type-id="some_prop"></conversation>

그리고 지시사항:

angular.module('myApp').directive('conversation', function() {
  return {
    scope: {
      typeId: '=',
    },
    link: function(scope, elm, attr) {

      scope.$watch('typeId', function(newValue, oldValue) {
          if (newValue !== oldValue) {
            // You actions here
            console.log("I got the new value! ", newValue);
          }
      }, true);

    }
  };
});

이것이 상위 스코프에서 값에 대한 지시문을 새로고침/새로 고치는 데 도움이 되기를 바랍니다.

<html>

        <head>
            <!-- version 1.4.5 -->
            <script src="angular.js"></script>
        </head>

        <body ng-app="app" ng-controller="Ctrl">

            <my-test reload-on="update"></my-test><br>
            <button ng-click="update = update+1;">update {{update}}</button>
        </body>
        <script>
            var app = angular.module('app', [])
            app.controller('Ctrl', function($scope) {

                $scope.update = 0;
            });
            app.directive('myTest', function() {
                return {
                    restrict: 'AE',
                    scope: {
                        reloadOn: '='
                    },
                    controller: function($scope) {
                        $scope.$watch('reloadOn', function(newVal, oldVal) {
                            //  all directive code here
                            console.log("Reloaded successfully......" + $scope.reloadOn);
                        });
                    },
                    template: '<span>  {{reloadOn}} </span>'
                }
            });
        </script>


   </html>
angular.module('app').directive('conversation', function() {
    return {
        restrict: 'E',
        link: function ($scope, $elm, $attr) {
            $scope.$watch("some_prop", function (newValue, oldValue) {
                  var typeId = $attr.type-id;
                  // Your logic.
            });
        }
    };
}

AngularJS 1.5.3 이후를 사용하고 있는 경우 지시어가 아닌 컴포넌트로 이동하는 것을 고려해야 합니다.이러한 기능은 디렉티브와 매우 유사하지만 단방향 바인딩이 업데이트될 때마다 호출되는 라이프 사이클 훅 중 하나인 $onChanges(changesObj)와 같은 매우 유용한 추가 기능을 포함합니다.

app.component('conversation ', {
    bindings: {
    type: '@',
    typeId: '='
    },
    controller: function() {
        this.$onChanges = function(changes) {
            // check if your specific property has changed
            // that because $onChanges is fired whenever each property is changed from you parent ctrl
            if(!!changes.typeId){
                refreshYourComponent();
            }
        };
    },
    templateUrl: 'conversation .html'
});

여기 컴포넌트에 대한 상세 설명서가 있습니다.

언급URL : https://stackoverflow.com/questions/20856824/angular-directive-refresh-on-parameter-change

반응형