1

我有一个范围变量“$scope.searchType”,默认情况下等于“createdAt”。在我的 HTML 中,我有更改范围变量值的选项:

<ul class="dropdown-menu" role="menu">
    <li><a ng-click="searchType = 'Anything'">Anything</a></li>
    <li><a ng-click="searchType = 'Payment'">Payment</a></li>
    <li><a ng-click="searchType = 'Total'">Total</a></li>
    <li><a ng-click="searchType = 'Tax'">Tax</a></li>
    <li><a ng-click="searchType = 'Payment Method'">Payment Method</a></li>
</ul>

在我的控制器中,我有以下内容可以监听更改:

$scope.$watch('searchType', function(newValue) {
    if(newValue == 'Payment') {
        $scope.searchTypeFilter = 'id';
        $scope.searchFiltered = true;
    } else if(newValue == 'Total') {
        $scope.searchTypeFilter = 'total';
        $scope.searchFiltered = true;
    } else if(newValue == 'Tax') {
        $scope.searchTypeFilter = 'tax';
        $scope.searchFiltered = true;
    } else if(newValue == 'Payment Method') {
        $scope.searchTypeFilter = 'paymentType';
        $scope.searchFiltered = true;
    } else {
        $scope.searchTypeFilter = '';
        $scope.searchFiltered = false;
        $scope.search = '';
    }
}, true);

由于某种原因, $scope.$watch 永远不会被调用。我无法弄清楚这是如何不起作用的,因为它曾经如此。这是“$scope.searchType”声明:

$scope.sortType = 'createdAt';
4

1 回答 1

2

您不需要添加 $watch,因为您有一个单击事件来设置您的过滤器变量。

您的 if/else 也可以使用 js 对象进行简化。

请看下面的演示或这个小提琴

angular.module('demoApp', [])
.controller('mainController', MainController);

function MainController($scope) {
    var filterMapping = {
        
        Payment: 'id',
        Total: 'total',
        Tax: 'tax',
        'Payment Method': 'paymentType',
        Default: ''
    };
    
    this.setNewFilter = function(name) {
        $scope.searchTypeFilter = filterMapping[name] || filterMapping['Default'];
        $scope.searchFiltered = $scope.searchTypeFilter != '' ? true: false;
    };
  
    this.setNewFilter(''); // init filter to anything
}

MainController.$inject = ['$scope'];
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demoApp" ng-controller="mainController as ctrl">
<ul class="dropdown-menu" role="menu">
    <li><a ng-click="ctrl.setNewFilter('Anything')">Anything</a></li>
    <li><a ng-click="ctrl.setNewFilter('Payment')">Payment</a></li>
    <li><a ng-click="ctrl.setNewFilter('Total')">Total</a></li>
    <li><a ng-click="ctrl.setNewFilter('Tax')">Tax</a></li>
    <li><a ng-click="ctrl.setNewFilter('Payment Method')">Payment Method</a></li>
</ul>
    {{searchFiltered}}<br/>
{{searchTypeFilter}}    
</div>

于 2015-06-21T19:42:22.813 回答