Elliot
Elliot

Reputation: 13835

set ng-model var to defualt value of input in angularjs

Lets say I have the following:

I want $scope.bookname's initial value to be 123. And if bookname is updated elsewhere, I'd like the value in the input to change (i.e. the model binding).

123 is set dynamically (from rails), so I cannot set it in javascript earlier (i.e. $scope.bookname = 123; will not work).

Any ideas how to accomplish this?

Upvotes: 0

Views: 821

Answers (2)

Foo L
Foo L

Reputation: 11137

The answer from ze bear is correct. The way to do it in rails is to make the JavaScript file an erb file and use <%= => tags around the rails variable.

Upvotes: 0

mnsr
mnsr

Reputation: 12437

A couple of ways you could do this off the top of my head (I'm not familiar with rails, but i'll try to make it vague enough to apply to all server side languages):

  • In your html, dynamically create a <script> tag and create a var BookName = 123; Where '123' is obviously the value of your server side variable. Then in your controller, initialise it: $scope.bookname = BookName;
  • In your html, create a hidden input, and dynamically give it a value. Then grab the value in your controller: $scope.bookname = $('#inputID').val();
  • You could create a json call and have your controller/service make a request and your server sends back the variable's value.

Also, here's another technique (blesh's answer): Angular js init ng-model from default values

Upvotes: 1

Related Questions