2013-07-31 51 views
4

HostingCtrl:AngularJS:無法從CTRL範圍變量的值轉換成指令

function HostingListCtrl($scope, Hosting) { 

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

HTML模板:

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

指令:

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) {       
     } 
    }; 
}); 

我試圖在指令中獲取itemsCount變量的值,但是當我嘗試console.log時,它的值爲空。 奇怪的是,整個CONSOLE.LOG範圍時,它的存在:

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 

而且當我檢查HTML源

<nav class="pagination" items-count="11" current-page="currentPage" items-per-page="5"> 

回答

4

隨着分離範圍和@符號,你需要使用$attrs.$observe('itemsCount', function(value) { ... }

參見http://docs.angularjs.org/guide/directive#attributes

當功能首先執行控制器(和鏈路),則@屬性不填充尚未。您會看到日誌中的值,因爲在展開$ scope對象時,該值已填充。