Joe
Joe

Reputation: 834

Directive scope gets overwritten

I have this directive and whenever I do a ng-repeat, for some reason when I used console.log it always return the last data from ng-repeat.

(function () {
    'use strict';

    angular
        .module('app.schoolAdmin')
        .directive('barGraph', barGraph);

    barGraph.$inject = ['$timeout'];

    function barGraph ($timeout) {
        var scope;
        var element;

        return {
            link: link,
            restrict: 'EA',
            scope: {
                data: '=',
                onClick: '&',
                methods: '='
            }
        };

        function init () {
            console.log("DATA", scope.data);
        }

        function link (_scope, _element) {
            scope = _scope;
            element = _element;

            $timeout(function () {
                init();

            }, 0);

        }
    }
})();

here is the code for the ng-repeat.(the data when using a json pipe is correct.)


            <div class="col-md-3"
                 ng-repeat="(key, group) in vm.analyticsData">
                 {{group | json}}
                 <h1>{{ key }}</h1>
                <div class="charts-container">
                    <div class="chart-block">
                        <bar-graph data="group"></bar-graph>

                    </div>
                </div>
            </div>

Upvotes: 0

Views: 42

Answers (1)

Abdelkarim EL AMEL
Abdelkarim EL AMEL

Reputation: 1533

$timeout(function () {
   init();
}, 0);

Your timeout above is causing the issue.

Remove it in order to fix the issue.

If you want to keep the $timeout, you can pass _scope to your init method like this :

  function init (data) {
    console.log("DATA", scope.data);
    console.log("REAL DATA", data);
  }

  function link (_scope, _element, attrs) {
    scope = _scope;
    element = _element;
    $timeout(function () {
      init(_scope.data);
    }, 0);

  }

Here's a sample jsfiddle

Upvotes: 2

Related Questions