IT story

Angular 지시문에서 데이터 변경 사항을 감시합니다.

hot-time 2020. 6. 29. 07:44
반응형

Angular 지시문에서 데이터 변경 사항을 감시합니다.


$watch내부에서 데이터를 조작 할 때 (예 : 데이터 삽입 또는 제거) Angular 지시문에서 변수를 트리거 할 수 있지만 해당 변수에 새 객체를 할당 할 수 없습니까?

현재 JSON 파일에서 간단한 데이터 세트를로드하고 있습니다. 내 Angular 컨트롤러 가이 작업을 수행하고 몇 가지 기능을 정의합니다.

App.controller('AppCtrl', function AppCtrl($scope, JsonService) {
    // load the initial data model
    if (!$scope.data) {
        JsonService.getData(function(data) {
            $scope.data = data;
            $scope.records = data.children.length;
        });
    } else {
        console.log("I have data already... " + $scope.data);
    }

    // adds a resource to the 'data' object
    $scope.add = function() {
        $scope.data.children.push({ "name": "!Insert This!" });
    };

    // removes the resource from the 'data' object
    $scope.remove = function(resource) {
        console.log("I'm going to remove this!");
        console.log(resource);
    };

    $scope.highlight = function() {

    };
});

나는이 <button>제대로 호출하는 $scope.add기능을하고, 새로운 개체가 제대로 삽입 $scope.data세트. 설정 한 테이블은 "추가"버튼을 누를 때마다 업데이트됩니다.

<table class="table table-striped table-condensed">
  <tbody>
    <tr ng-repeat="child in data.children | filter:search | orderBy:'name'">
      <td><input type="checkbox"></td>
      <td>{{child.name}}</td>
      <td><button class="btn btn-small" ng-click="remove(child)" ng-mouseover="highlight()"><i class="icon-remove-sign"></i> remove</button></td>
    </tr>
  </tbody>
</table>

그러나 내가 감시하도록 설정 한 지시문 $scope.data은이 모든 일이 발생해도 해고되지 않습니다.

HTML로 태그를 정의합니다.

<d3-visualization val="data"></d3-visualization>

다음 지시문과 관련이 있습니다 (질문을 위해 다듬어 짐).

App.directive('d3Visualization', function() {
    return {
        restrict: 'E',
        scope: {
            val: '='
        },
        link: function(scope, element, attrs) {
            scope.$watch('val', function(newValue, oldValue) {
                if (newValue)
                    console.log("I see a data change!");
            });
        }
    }
});

I get the "I see a data change!" message at the very beginning, but never after as I hit the "add" button.

How can I trigger the $watch event when I'm just adding/removing objects from the data object, not getting a whole new dataset to assign to the data object?


You need to enable deep object dirty checking. By default angular only checks the reference of the top level variable that you watch.

App.directive('d3Visualization', function() {
    return {
        restrict: 'E',
        scope: {
            val: '='
        },
        link: function(scope, element, attrs) {
            scope.$watch('val', function(newValue, oldValue) {
                if (newValue)
                    console.log("I see a data change!");
            }, true);
        }
    }
});

see Scope. The third parameter of the $watch function enables deep dirty checking if it's set to true.

Take note that deep dirty checking is expensive. So if you just need to watch the children array instead of the whole data variable the watch the variable directly.

scope.$watch('val.children', function(newValue, oldValue) {}, true);

version 1.2.x introduced $watchCollection

Shallow watches the properties of an object and fires whenever any of the properties change (for arrays, this implies watching the array items; for object maps, this implies watching the properties)

scope.$watchCollection('val.children', function(newValue, oldValue) {});

Because if you want to trigger your data with deep of it,you have to pass 3th argument true of your listener.By default it's false and it meens that you function will trigger,only when your variable will change not it's field.


My version for a directive that uses jqplot to plot the data once it becomes available:

    app.directive('lineChart', function() {
        $.jqplot.config.enablePlugins = true;

        return function(scope, element, attrs) {
            scope.$watch(attrs.lineChart, function(newValue, oldValue) {
                if (newValue) {
                    // alert(scope.$eval(attrs.lineChart));
                    var plot = $.jqplot(element[0].id, scope.$eval(attrs.lineChart), scope.$eval(attrs.options));
                }
            });
        }
});

참고URL : https://stackoverflow.com/questions/13980896/watching-for-data-changes-in-an-angular-directive

반응형