0

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>
MSclavi
  • 427
  • 2
  • 10
Joe
  • 774
  • 6
  • 23

1 Answers1

2
$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

Abdelkarim EL AMEL
  • 1,515
  • 1
  • 10
  • 10
  • can you explain why? i don't see a reason why. (non sarcastic) – Joe Apr 16 '19 at 06:19
  • 2
    the `$timeout` will not block the execution of your code, your `scope.data` will get overridden since the call to the `init` method is delayed even if you put a 0, thery will be a delay since the calls are placed in a queue, have a look at this [Q&A](https://stackoverflow.com/questions/33955650/what-is-settimeout-doing-when-set-to-0-milliseconds) for details. – Abdelkarim EL AMEL Apr 16 '19 at 08:34
  • does angular directives share variables? and not a separate instance? – Joe Apr 16 '19 at 10:33
  • 1
    it's not shared, but you aren't using the `_scope` variable which contains the actual data. when you assign that to `scope` variable, it gets overridden since the second iteration happens before executing the `console.log` in your init method which uses `scope` not `_scope` – Abdelkarim EL AMEL Apr 16 '19 at 10:41