Angular 中的指令未获取数据

Directive in Angular not getting DATA

我的指令没有得到任何数据。在控制台中,我得到了总项目数:未定义。即使我从我的控制器传递一个数字或一个值,它都是一样的。我的模板 URL 也没有得到任何值。提前谢谢你。

    (function(){
    'use strict';
    angular
        .module('adminApp')
        .directive('pagination', paginate);

    function paginate() {
        return {
            restrict: 'A',
            scope: {
                totalItems:  '=',
                itemsOnPage: '=',
                pageUrl:         '=',
                currentPage: '='

            },
            templateUrl: 'assets/js/admin/templates/pagination-template.html',
            link: function(scope, element, attrs){
                console.log("Total Items: ",scope.totalItems);
            },
        };
    }
})();

HTML:

<div ng-if="vm.promiseReady">
    <div pagination totalItems="300" pageUrl="vm.pageUrl" currentPage="vm.currentPage"></div>
</div>

HTML 模板:

<div class="pagination">
<div class="pagination-bttns">
    <a class="pagination-bttn"
       href="#"
       ng-if="currentPage != 1"
       ng-href="{{pageUrl}}{{currentPage-1}}"
    >
    PREVIOUS {{totalItems}}
    </a>

    <a class="pagination-bttn"
       href="#"
       ng-if="currentPage != totalItems"
       ng-href="{{pageUrl}}/{{currentPage+1}}"
    >
    NEXT
    </a>
</div>

摘自 angular documentation on 指令,在标题为 "Normalization" 的部分中。

Angular normalizes an element's tag and attribute name to determine which elements match which directives. We typically refer to directives by their case-sensitive camelCase normalized name (e.g. ngModel). However, since HTML is case-insensitive, we refer to directives in the DOM by lower-case forms, typically using dash-delimited attributes on DOM elements (e.g. ng-model).

尝试交换

<div pagination totalItems="300" pageUrl="vm.pageUrl" currentPage="vm.currentPage"></div>

到(现在注意 dash-delimited 属性)

<div pagination total-items="300" page-url="vm.pageUrl" current-page="vm.currentPage"></div>

这是因为,如文档所述,所有 HTML 属性必须是 dash-delimited 而不是驼峰式。

指令的作用域需要绑定一个变量。您只是添加了一个属性值。这样的事情会解决它。

<div ng-if="vm.promiseReady">
    <div pagination ng-init="vm.totalItems=300" total-items="vm.totalItems" pageUrl="vm.pageUrl" currentPage="vm.currentPage"></div>
</div>

<div ng-if="vm.promiseReady">
    <div pagination total-items="300" pageUrl="vm.pageUrl" currentPage="vm.currentPage"></div>
</div>

     link: function(scope, element, attrs){
            scope.totalItems = parseInt(attrs.totalItems);
            console.log("Total Items: ",scope.totalItems);
        },

在后一种情况下,我可能会从指令的 public 范围中删除 totalItems。

在Html中将totalItems更改为total-items和其他类似的属性。 Angular 指令将在范围对象中将散列分隔的文本更改为驼峰式。所以,你的新 Html 应该是:

<div ng-if="vm.promiseReady">
    <div pagination total-items="300" page-url="vm.pageUrl" current-page="vm.currentPage"></div>
</div>