AngularJS – Issues passing attributes to directive – Receive undefined value for each of them

I´m working on a directive that receives four parameters, each of them is binded to the directive scope.

The issue is that the directive receives all the values as undefined, the data exists, and it´s loaded. I thought about the async loading of data, but, “page” isn´t async, and it´s published in the scope from the very beginning.

Plunker here: http://plnkr.co/edit/4NEciJZBFZOdJZqR1V6D

HTML:

<div ng-controller="myController">
    <itemscounter offset="dataObject.offset" limit="dataObject.limit" total="dataObject.total" page="dataObject.page"></itemscounter>
</div>

JS:

var myApp = angular.module("myApp", []);

  myApp.controller("myController", function($scope){
    $scope.dataObject = {
       offset: 1,
       limit: 20,
       total: 25,
       page: 2
    }
})

myApp.directive("itemscounter", function() {

return {
    restrict: "E",
    scope: {
        page: '=',
        total: '=',
        offset: '=',
        limit: '=' 
    },
    template: "<div>Showing products {{offset}} to {{limit}} from {{total}} (Page {{page}})</div>",
    link: function (scope, element, attrs) {

    }
}

})

Any help will be very appreciated.

Thanks so much in advance,

Guillermo

Answer

The only thing that I saw wrong, based on your description and example, is that the data model was declared outside the controller scope. I created a working version on plunker. The only thing I changed was moving the data model into the $scope of the controller so that it could be bound to the directive by Angular.

I changed this:

var dataObject = {
  offset: 1,
  limit: 20,
  total: 25,
  page: 2
}

var myApp = angular.module("myApp", []);

myApp.controller("myController", function($scope){

})

to this:

var myApp = angular.module("myApp", []);

myApp.controller("myController", function($scope){
  $scope.dataObject = {
    offset: 1,
    limit: 20,
    total: 25,
    page: 2
  };
})

I hope this helps.

Leave a Reply

Your email address will not be published. Required fields are marked *