Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

angularjs - $scope.$watch with filtered scopes as output

This question is based in the answer provided here

I want to output the result from a lodash function applied to a scope ($scope.names) when another scope ($scope.switch) is set to true, and to output the result of that lodash function applied to a filtered scope when $scope.switch is set to false.

So my ng-repeat would be like this:

<ul>
    <li ng-repeat="things in (filtered=(names | filter:filterType))">{{things}}</li>
</ul>

I use two ng-click to change the state of $scope.switch and to apply/unapply the filter:

<a ng-click="switch = false; filterType=''">unswitch - No Filters</a><br><br>
<a ng-click="switch = true; filterType={name:'!Jimmy'}">switch - Not Jimmy</a>

And I used this code in order to watch the changes in $scope.switch:

$scope.$watch('switch', function() {
      $scope.thingScope =$scope.switch ? _.map($scope.names,"styles") : _.map($scope.filtered,"styles");
    });

Here is the working plunkr with all the code (it's much easier to notice the problem here)

The problem is that the output of $scope.thingScope doesn't correspond to the values showed in the ng-repeat (right now every time I click, it shows the values of the previous one, that is, it goes one step behind). Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Ok, I found few problems.

0 - You are working with a generated list element (Filtered. which is the result of apply the filter over names). When the switch change, the generated list is not finished. So, you will not find the elements.

1 - You have a lot of elements Trying to work over the same (the Swtich/Filter over names).

2 - You are showing using: $scope.thingScope = $scope.switch ? _.map($scope.names,"styles") : _.map($scope.filtered,"styles"); So, you are showing $scope.names when $scope.switch == true. So wrong conditional.

3 - You are applying first the change of the switch and then the filterType in the ng-click.

So, you can do 2 things.

  1. Work with duplicated filters in 2 places (Not recommended.)
  2. The ng-repeat work with the processed-list. And work all the filters in the controller. As @shaunhusain did it.

P.S. I think it could be cleaner with an active to filter. And not by Name, check this Plnkr: http://plnkr.co/edit/4uJ5AxP9xntgBe1hQrBW?p=preview

You can select by Name (only clicking) but you must click again in update filters to apply changes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...