Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: Can't get a value of variable from ctrl scope into directive

HostingCtrl:

function HostingListCtrl($scope, Hosting) {

    Hosting.all().success(function(data) {
        $scope.hostings = data;
    }); 
}

HTML template:

 <pagination items-count="{{hostings.length}}" current-page="currentPage" items-per-page="{{itemsPerPage}}"></pagination>

Directive:

admin.directive('pagination', function() {
    return {
        restrict: 'E',
        replace: true,        
        templateUrl: "<%= asset_path('angular/templates/ui/pagination.html') %>",
        scope: {            
            currentPage: '=',
            itemsCount: '@',
            itemsPerPage: '@'
        },
        controller: function($scope, $element, $attrs) {
            console.log($scope);
            console.log($scope.itemsCount);          
        },
        link: function(scope, element, attrs, controller) {                         
        }
    };
});

I'm trying to get hold of value of itemsCount variable in the directive but when I try to console.log it, the value is empty. Strange thing is that when console.log whole scope, it's there:

Scope {$id: "005", $$childTail: null, $$childHead: null, $$prevSibling: null,
  $$nextSibling: null…}
  $$asyncQueue: Array[0]
  $$childHead: null
  $$childTail: null
  $$destroyed: false
  $$isolateBindings: Object
  $$listeners: Object
  $$nextSibling: Child
  $$phase: null
  $$prevSibling: null
  $$watchers: Array[3]
  $id: "005"
  $parent: Child
  $root: Scope
  currentPage: 1
  itemsCount: "11"
  itemsPerPage: "5"
  this: Scope
  __proto__: Object

Also when I check the HTML source

<nav class="pagination" items-count="11" current-page="currentPage" items-per-page="5">
like image 903
Marek Takac Avatar asked Jul 31 '13 19:07

Marek Takac


1 Answers

With an isolate scope and the @ notation, you need to use $attrs.$observe('itemsCount', function(value) { ... }.

See http://docs.angularjs.org/guide/directive#attributes

When the controller (and link) functions first execute, the @ properties are not populated yet. You see the value in the log because by the time you expand the $scope object, the value has been populated.

like image 146
Mark Rajcok Avatar answered Sep 20 '22 03:09

Mark Rajcok