2

I am working on angularJS and node.js application and got stuck on this silly bug. I am trying for few hours, but it is still giving me a headache. I will thank ful if any of you have a solution or suggestions.

Frontend

<md-input-container class="md-block"  flex-gt-xs>
            <label>Service Category</label>
            <md-select ng-model="commissionScheme.category" ng-model-options="{trackBy: '$value._id'}">
              <md-option ng-repeat="srv in service_categories" ng-value="srv">
                {{srv.name}}
              </md-option>
            </md-select>
          </md-input-container>  
          <md-input-container class="md-block"  flex-gt-xs>
            <label>Service</label>
            <md-select ng-model="commissionScheme.service" ng-model-options="{trackBy: '$value._id'}">
              <md-option ng-repeat="srv in services" ng-value="srv">
                {{srv.name}}
              </md-option>
            </md-select>
          </md-input-container>

Controller

$http.get("api/models/service_category").success(function(response, status, headers){
        $scope.service_categories = response;
    });

    $scope.$watch("commissionScheme.category",function(newValue,oldValue){
        var url = "api/models/service";
        if(angular.isObject(newValue)){
            url += "?category._id="+newValue._id;
        }
        $http.get(url).success(function(response, status, headers){
            $scope.services = response;
        });
    });

Output You guys can see in service drop down, I am getting a repetitive value. This is what I get..

But when i click on anywhere on this page.. it turns like this. when I click anywhere on this page

I feel like the $watch is called twice but ... I am not getting where I am wrong in the code.

Even on the network inspect you can see two calls by service?category._id=49489492u4...45

network inspect

Is there any directive, I can use to get rid of this bug? Thank you for all for you time and efforts. :)

jatinder bhola
  • 385
  • 1
  • 7
  • 23
  • How about a plunker? – Mikko Viitala Aug 09 '16 at 19:08
  • As explained in [this answer](http://stackoverflow.com/a/20942931/548997) it could be a result of the `$watch` being initialized. You should implement an `if(newValue !== oldValue)` check before calling the code inside your `$watch`. Or maybe just use `ng-change` on your select element. – Lex Aug 09 '16 at 19:33

0 Answers0