AngularJS:无法将 ctrl 范围中的变量值获取到指令中 [英] AngularJS: Can't get a value of variable from ctrl scope into directive

查看:34
本文介绍了AngularJS:无法将 ctrl 范围中的变量值获取到指令中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HostingCtrl:

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 整个范围时,它就在那里:

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

还有当我检查 HTML 源代码时

Also when I check the HTML source

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

推荐答案

使用隔离范围和 @ 表示法,您需要使用 $attrs.$observe('itemsCount',函数(值){ ... }.

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

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

当控制器(和链接)函数第一次执行时,@ 属性还没有被填充.您会在日志中看到该值,因为在您展开 $scope 对象时,该值已被填充.

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.

这篇关于AngularJS:无法将 ctrl 范围中的变量值获取到指令中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆