如何在rails中初始化Angularjs ng-model

Gin*_*Jim 3 javascript ruby ruby-on-rails erb angularjs

关于使用angularjs双向绑定和rails erb文件的问题.

假设我的.erb文件中的输入值具有原始值,即

example.erb

<input type="text" value=" <%= @item.title %> " ng-model ="item.title">
Run Code Online (Sandbox Code Playgroud)

正如您在上面的示例中所注意到的那样,输入也与angularJs模型绑定.example.js

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

我发现原始的@ item.title被angularJs模型值覆盖.但是,我希望事情以相反的方式发生,也就是说,角度js模型是通过.erb文件中的值初始化的.我怎样才能做到这一点?

我试图将example.js放入资产管道.即example.js.erb

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

但是@item总是在管道中.我想@item只在视图中可用?

Dav*_*yon 7

你可以使用ng-init这个:

<input type="text" ng-init="item.title = '<%= @item.title %>'" ng-model ="item.title">
Run Code Online (Sandbox Code Playgroud)