Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doesn't work two ways of filtering (AngularJS)

I'm trying to make two ways of filtering (via clicking on letters or via typing in input field).

<body ng-controller="MainController">
    <ul search-list=".letter" model="search">
        <li class="letter" ng-repeat="letter in alphabet.letter">{{ letter }}</li>
    </ul>

    <div class="container" ng-controller="CountriesController">

        <input id="q" type="text" ng-model="search " />
        <ul>
            <li ng-repeat="country in countries.country | filter:search:startsWith">{{ country }}</li>
        </ul>

    </div>
</body>

and js:

var app = angular.module('demo', []);
var controllers = {};
var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");



app.directive('searchList', function() {
    return {
        scope: {
            searchModel: '=model'
        },
        link: function(scope, element, attrs) {
            element.on('click', attrs.searchList, function() {
                scope.searchModel = $(this).text();
                scope.$apply();
            });
        }
    };
});

controllers.MainController = function($scope) {
    $scope.setTerm = function(letter) {
        $scope.search = letter;
    };
    $scope.alphabet = {
      letter: alphabet
    }
};
controllers.CountriesController = function($scope){

  $scope.countries = {
    country:['Ukraine','Urugvai','Russia','Romania','Rome','Argentina','Britain']
  }
  $scope.startsWith = function (actual, expected) {
    var lowerStr = (actual + "").toLowerCase();
    return lowerStr.indexOf(expected.toLowerCase()) === 0;
  }
};



app.controller(controllers);

On first look everything is working fine, but it is so only on first look...

When at first I click on any letter - filter works good. When then I'm typing in input field - filter works good. But after I typed in input field or delete text from there via 'backspace' button - filter by clicking on letters stops working...

Why it works like this and how I can fix this issue? Here is my DEMO

Thanx in advance!

like image 875
Johnny Juarez Avatar asked Oct 20 '22 08:10

Johnny Juarez


1 Answers

The problem fount for using two controler's. If you remove CountriesController , then everything working good.

The Search values was confused with which controller using that scope object.I think you don't need implement two controller for this scenario

See the working demo if you remove CountriesController.

like image 94
Ramesh Rajendran Avatar answered Oct 21 '22 22:10

Ramesh Rajendran