AngularJS:无法从ctrl范围获取变量值到指令

时间:2021-08-08 19:43:41

HostingCtrl:

HostingCtrl:

function HostingListCtrl($scope, Hosting) {

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

HTML template:

HTML模板:

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

我试图在指令中获取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

Also when I check the HTML source

当我检查HTML源代码时

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

1 个解决方案

#1


4  

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

使用隔离范围和@符号,您需要使用$ attrs。$ observe('itemsCount',function(value){...}。

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

请参见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.

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

#1


4  

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

使用隔离范围和@符号,您需要使用$ attrs。$ observe('itemsCount',function(value){...}。

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

请参见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.

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