AngularJS 指令作用域绑定未立即填充到 link 函数中

AngularJS directive scope binding not populated immediately in link function

我正在编写以下指令:

.directive('mypagination', function () {
    return {
        restrict: 'E',
        scope: {
            pageCount: "=",
        },
        template: "{{pageCount}}",
        link: function ($scope, $element, $attrs) {
            $scope.pages = [];
            for (var i = 1; i <= $scope.pageCount; i++) {
                $scope.pages.push(i);
            }
        }
    }
})

我的问题是 for 循环中的 $scope.pageCount 设置为 0,但模板中的 {{pageCount}} 呈现正确的值。

在 HTML 中,指令是这样调用的:

<mypagination page-count="mjaController.pages.length" 
              on-page-change="mjaController.fetchStuff(page)">
</mypagination>

为什么 pageCount 的值在 link 函数中为 0,但在页面上正确呈现?

当你的 link 函数执行时 pageCount 可以是 0 因为它绑定到 mjaController.pages.length 属性 我猜是检索来自 API 并且是 async 电话。一旦 mjaController.pages 填充了一些数据,然后 pageCount 被设置为其长度并通过 $digest 循环显示在 template 上,但 link 函数将不会执行再次。要使其按预期工作,请执行以下操作

.directive('mypagination', function () {
    return {
        restrict: 'E',
        scope: {
            pageCount: "=",
        },
        template: "{{ pages()|json }}",
        link: function ($scope, $element, $attrs) {
            $scope.pages = function () {
              var pages = [];
              for (var i = 1; i <= $scope.pageCount; i++) {
                pages.push(i);
              }
              return pages;
            }
        }
    }
})

$scope 中添加一个 method 并在模板中使用它的 return 值。

使用$watch等待数据从服务器到达:

.directive('mypagination', function () {
    return {
        restrict: 'E',
        scope: {
            pageCount: "<",
            onPageChange: "&"
        },
        template: "{{pageCount}}",
        link: function (scope, elem, attrs) {
            scope.$watch("pageCount", function(newValue) {
                if(newValue)
                    scope.pages = [];
                    for (var i = 1; i <= newValue; i++) {
                        scope.pages.push(i);
                    }
                }
            });
        }
    }
})

一般来说,这种类型的数据操作应该在指令的控制器中完成,以利用 life-cycle hooks such as $onChanges. For more information, see AngularJS Developer Guide - Component-based Application Architecture