limit
limit

Reputation: 647

Angular JS - Update Scope value on click

Right now I am passing my parameter through the state like:

        .state('app.listing', {
        url: '/ad/listing/:adId/{type}',
        params: {
          adId: {
            value: "adId",
            squash: false
          }, type: {
            value: null,
            squash: true
          }
        },

This works as I can get "type" from $stateParams and update my get request.

Is there not a way to do this from a click event and not use $stateParams for passing the "type" param?

I basically have a button that filters results and passes the type param from the button. It would be a lot easier if I can just attach a click event to it which then updates my get request.

Just messing around I tried doing something like

  $scope.filter = function(type) {
    if(type) {
      return type;
    }
    return '' ;
  }

    $scope.type = $scope.filter();

Service is like

$http.get(API_ENDPOINT.url + '/listing/' + adId, {
        params: {
          page: page,
          type: type // essentially $scope.type 
        },
      }).

and then on my button I have

 <button ng-click="filter('2')"></button>

^ This will pass 2 for type, but won't reinit the http get call on click. Do I need to broadcast the change is there a simple way to do this?

Does this even make sense? The code above is just mock to give an idea, but open to suggestions if any.

Upvotes: 0

Views: 472

Answers (3)

Shintu Joseph
Shintu Joseph

Reputation: 962

Angular never requires you to make broadcasts to reflect changes made to scopevariables via the controller

var typeWatcher = '1';
$scope.filter = function(type){

    if (type !== typeWatch)
        {

            $http.get(API_ENDPOINT.url + '/listing/' + adId, {
               params: {
                  page: page,
                  type: type // essentially $scope.type 
              },
           });
           typeWatcher = type;
        }

};

Upvotes: 1

Varit J Patel
Varit J Patel

Reputation: 3520

Well, To call $http.get method on click,

$scope.filter = function(type) {
  if(type) {
    //call the method using service.methodName
    return type;
  }
  return '' ;
}

and wrap that $http.get method to one function.

Hope it helps you.

Cheers

Upvotes: 0

Nishant
Nishant

Reputation: 916

You can wrap your get call in a function & call it after the filter function in ng-click

$scope.functionName = function () {
  return $http.get(API_ENDPOINT.url + '/listing/' + adId, {
    params: {
      page: page,
      type: type // essentially $scope.type 
    }
  })
}

then in HTML

<button ng-click="filter('2'); functionName()"></button>

Upvotes: 0

Related Questions