2

I have a select dropdown in HTML that has strings for display and numbers as its value. Each number is the ID of a resource that can be queries via a REST HTTP URL.

How do I bind the changing selection state of a select to a property on an Angular controller? Is it correct to use ng-change? What's the most Angularian and declarative way of doing this?

Assume for now that the select is scoped to the same controller as the function that makes the REST request.

2
  • http://docs.angularjs.org/tutorial/step_04 Commented Mar 29, 2013 at 20:06
  • I'm not seeing that it matches what I need just quite. Perhaps I should simplify my question, I want a change in a select to trigger a function in the controller that includes the new value of the select. I think then the function can take that value and append it to a REST query. I can bind the select already to a property on the controller, but changing the property doesn't trigger a function. Commented Mar 29, 2013 at 20:13

1 Answer 1

5

One way is to use $watch on the ng-model property in scope for the select.

$scope.selectModel='foo';
$scope.otherProperty= /* ....*/

$scope.$watch( 'selectModel', function(){
   $http.get(url, { keyName: $scope.selectModel).success(function(response) {
           $scope.otherProperty=response;
    });

})
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, I also found that that the ng-change attribute will work as well.
as i prefaced..this is one way. I presented this one because can use $watch for many other uses within app and is extremely valuable tool in your angular arsenal
Thanks charlietfl, I agree your answer is better and broader, that's why I marked it accepted and upvoted it. I was just noticing that there is at least one other select specific way.
curious what other way is, I just started with angular not long ago, still figuring out variations
As I said, ng-change allows you to call a function on the controller, which in turn can make the AJAX call. I think yours is a better approach because at the moment I'm having issues with two way binding, going from model back to the view.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.