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.searchType'声明:

$scope.sortType = 'createdAt'; 
+0

贵'下拉-menu' HTML被包裹在你的推杆了'$ watch'控制器? –

+0

你确定手表和下拉菜单在同一范围内吗? – ajmajmajma

+0

是的,我相信他们自$ scope。$ watch在页面加载时输入一次。但之后它永远不会再运行。 – Niraj

回答

2

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

此外,您的if/else可以用js对象进行简化。

请看下面的演示或这个fiddle

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>

+0

你是救生员。非常感谢!! :) – Niraj

+0

另外 - 为什么不看这种情况下的工作? – Niraj

+0

手表也可以在这里使用。看到这[jsfiddle](http://jsfiddle.net/awolf2904/1u007t1s/)。我不知道你的代码有什么问题。无论如何,我不会在这里添加手表,因为如果您的应用越来越大,它可能会降低您的应用速度。因为它会在每个摘要循环中检查。 – AWolf