Search code examples
javascriptangularjsangular-ngmodeljqvmap

How can I fill ng-model query for filtering data using a javascript?


I use AngularJS for storing data in JSON and want to filter shown on the page items. Each item includes country code as a property:

[
 {
  "id": "1",
  "code": "us"
 },
 {
  "id": "2",
  "code": "ca"
 }
]    

I want to use Jquery VMap to filter items. When I click to the region, the list of items should be filtered. When I use simple "input" field, the list is filtered. But when I use following code that is executed when I click to the county, nothing happens:

onRegionClick: function(element, code, region)
 {
  document.getElementById("query").value = code;
  function updateQuery($scope) {
   $scope.query = code;
   $scope.$digest();
  }
 }

How can I make Angular knows about the change of "query" or is there any better solution? Link to the fiddle: http://jsfiddle.net/47RLz/4/


Solution

  • Try this:

    onRegionClick: function(element, code, region)
     {
        var e = document.getElementById("query");
        var scope = $(e).scope();
        scope.$apply(function() {
            scope.query = code;
        });
    
     },
    

    Explanation

    In angular, you can retrieve the scope of any element by calling scope() on the jQuery element. Once you have the scope, code is assigned to the query variable on the scope.

    Since the click handler is executing outside of the angular context, the assignment is wrapped in an $apply block to trigger a $digest cycle and update the views.

    Demo Fiddle