7

I'm trying to bind the value from an input field to the parameter of my method on ng-click. Here's what I got, but it doesn't work, and I am not too sure if it's possible to do it this way?:

<input type="text" name="name" value="{{post.PostId}}" />
<button ng-click="getById(post.PostId)"></button>
<h1>{{post.Title}}</h1>


$scope.getById = function (id) {
        console.log(id);
        return $http.get('/api/Post/' + id);
    }
2
  • what problem you are getting now after changing code to @JDTLH9 suggestion? Commented Jul 5, 2015 at 19:23
  • Well the problem is that the title of the post isn't appearing at all in the h1 tag Commented Jul 6, 2015 at 11:40

1 Answer 1

22

You should use ng-model directive for your input element.

Markup

 <input type="text" name="name" ng-model="post.PostId" />
 <button ng-click="getById(post.PostId)"></button>
 <h1>{{post.Title}}</h1>

This will take care of 2-way model binding to your property post.PostId. Your ng-click directive will pick up the correct value entered in input element.

See my working Plunk :)

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

2 Comments

Well it doesn't seem to work, but I added more code to the original post so that you can see the getById :)
@btmach it should work as you wanted. Please see the link to the Plunk in my edited answer.

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.