3

A question about using angularjs two way binding and in rails erb files.

Suppose value of input in my .erb file has an original value i.e.

example.erb

<input type="text" value=" <%= @item.title %> " ng-model ="item.title">

As you may notice in above example, the input is also binded with a angularJs model. example.js

mayApp.controller('newItemController', function itemController($scope) { 
   $scope.item = {title:"angularJs model value", price: 1000}
}

I found that the original @item.title is overridden by the angularJs model value. However, I want things happen in the opposite way, that is, the angular js model is initialised by value from .erb file. How can I do that?

I have tried to put example.js into asset pipeline. i.e. example.js.erb

mayApp.controller('newItemController', function itemController($scope) { 
   $scope.item = {title:"<%= @item.title %>", price: 1000}
}

but the @item is alway nil in the pipeline. I suppose the @item is only available in views?

4
  • AngularJS knows nothing and cares not about your rails model. Also, rails assets are not in scope of your rails model/controller so no wonder @item.title is undefined in example.js.erb. Commented Nov 30, 2013 at 15:53
  • @Stewie I agree with you. I know why this happened. Do you have any suggestions about how to initialise Angular model with value of rails models. Commented Nov 30, 2013 at 15:58
  • As a quick solution you might try to embed your example.js <script> into example.erb view partial. That way <%= @item.title %> will/should be interpolated with your item model while generating the html. Commented Nov 30, 2013 at 16:07
  • This is actually a very sensible question. Commented May 9, 2014 at 11:28

1 Answer 1

7

You can use ng-init for this:

<input type="text" ng-init="item.title = '<%= @item.title %>'" ng-model ="item.title">
Sign up to request clarification or add additional context in comments.

1 Comment

ok, updated. maybe ng-value will only work with other input types.

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.