AngularJS:Can't将变量的值从ctrl作用域获取到指令中

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

本文关键字:ctrl 作用域 获取 指令 变量 Can AngularJS      更新时间:2023-09-26

主机控制:

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">

对于隔离作用域和@表示法,您需要使用$attrs.$observe('itemsCount', function(value) { ... }

请参阅http://docs.angularjs.org/guide/directive#attributes

当控制器(和链接)功能首次执行时,尚未填充@属性。您可以在日志中看到该值,因为当您展开$scope对象时,该值已被填充。