0

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?

Elliot
  • 13,580
  • 29
  • 82
  • 118

2 Answers2

1

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

Community
  • 1
  • 1
mnsr
  • 12,337
  • 4
  • 53
  • 79
  • 2
    He could also directly capture it with angular, using `angular.value()` in a script tag. The script tag would need to be placed after the angular app inclusion. – holographic-principle Jul 01 '13 at 02:18
0

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.

Foo L
  • 10,977
  • 8
  • 40
  • 52