In the process of developing an Angular (1.2.1) application, I encountered a situation where I have a directive that includes an ng-repeat
in its template. The code snippet looks something like this:
<div ng-repeat="item in list | filter: filterList"></div>
<button ng-click="setColorMode('red')">Show only red items</button>
<button ng-click="setSizeMode('small')">Show only small items</button>
<!-- etc... -->
This setup also involves functionality within the directive's controller:
$scope.list = [
{ color: 'red', size: 'large' },
{ color: 'blue', size: 'small' }
//...
]
$scope.colorMode = null;
$scope.sizeMode = null;
$scope.setColorMode = function(value){$scope.colorMode = value;}
$scope.setSizeMode = function(value){$scope.sizeMode = value;}
$scope.filterList = function(item){
if ($scope.colorMode){
if ($scope.colorMode != item.color) return false;
}
if ($scope.sizeMode){
if ($scope.sizeMode != item.size) return false;
}
return true;
}
The colorMode
and sizeMode
variables are initialized as null, displaying all items regardless of color or size initially. However, the user has the option to filter the list based on color, size, or both by setting corresponding $scope.___mode
variables, which triggers the filter function to display only matching items.
Despite setting these variables, the issue arises when the data bound to the ng-repeat does not update upon toggling between modes. The filter function fails to re-execute, resulting in unchanged contents until there is a change in the actual data.
I assumed that Angular would automatically watch for changes in these scope values since they directly influence the filter function used in the ng-repeat. Unfortunately, this is not the case, leaving me with the question:
What is the most effective approach to achieve the desired functionality?
One workaround could involve modifying the data array within the mode setter functions. However, considering that the data is shared across different controllers through a service, this solution may not be ideal. Therefore, I am seeking a cleaner and more efficient implementation to address this issue.