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

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of AngularJS – Issues passing attributes to directive – Receive undefined value for each of them without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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.

We are here to answer your question about AngularJS – Issues passing attributes to directive – Receive undefined value for each of them - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji