ng-click值更改+ $ scope.watch绑定无法正常工作

时间:2015-06-21 18:48:53

标签: javascript angularjs angularjs-scope angularjs-ng-click angularjs-watch

我有一个范围变量' $ 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永远不会被调用。我不知道它以前是如何工作的。这是&#39; $ scope.searchType&#39;声明:

$scope.sortType = 'createdAt';

1 个答案:

答案 0 :(得分:2)

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

你的if / else也可以用js对象简化。

请查看下面的演示或此fiddle

&#13;
&#13;
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'];
&#13;
<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>
&#13;
&#13;
&#13;