Angularjs需要在ng-change之前更新ng-model

时间:2016-04-19 17:55:23

标签: javascript angularjs

我创建了customdirective,并希望在ng-change fire之前进行ng-model更新。目前在udpate ng-mdoel值之前的ng-change fire是我的代码。

当我在下拉列表中更改页码时,将出现主要问题。它以先前的值警告。我认为在ng-change fire之后ng-mdoel更新。但我想在ng-change之前进行ng-model fire。

app.directive('bottomPagination', function () {
    var directive = {
        templateUrl: '/App/Common/directives/bottomPagination.html',
        restrict: 'A',
        replace: true,
        scope: {
            currentPage: '=',
            changePageSize: '&'
        }
    };
    return directive;
});

//here is html directive (/App/Common/directives/bottomPagination.html)

       <select  id="pagesizeddl" ng-model="pageSize" ng-change="changePageSize()">
                            <option>5</option>
                            <option>10</option>
                            <option>20</option>
                            <option>30</option>
                        </select>

// here is my html page where i used directive


<div data-ng-controller="ProductsList as vm">
                <div data-bottom-pagination
                        data-page-size="vm.paging.pageSize"
                        data-change-page-size="vm.changePageSize()"
                         >
                    </div>
  </div>

// This is contrller
(function () {
    // Start Products List function
    var ListControllerId = 'ProductsList';
    angular.module('app').controller(ListControllerId,
        ['$scope', ListController]);

    function ListController($scope) {
        var vm = this;

        vm.paging = {
            pageSize: 10
        }; 

        vm.changePageSize = changePageSize;

        function changePageSize() {
            alert(vm.paging.pageSize);
        }
    }
})();

1 个答案:

答案 0 :(得分:1)

您好,我最近遇到了同样的问题。

我的最佳实践解决方案是在指令模板中的ng-change函数中添加一个参数。您需要将参数添加为JSON对象!

Film

该属性&#34; pageSize&#34; (JSON对象)将与指令函数vm.changePageSize(pageSize)的参数匹配。因此,两者都必须具有相同的名称!

<select  id="pagesizeddl" ng-model="pageSize" ng-change="changePageSize({pageSize:pageSize})">
                        <option>5</option>
                        <option>10</option>
                        <option>20</option>
                        <option>30</option>
                    </select>

现在你只需改变你的控制器功能:

<div data-ng-controller="ProductsList as vm">
            <div data-bottom-pagination
                    data-page-size="vm.paging.pageSize"
                    data-change-page-size="vm.changePageSize(pageSize)"
                     >
                </div>