Angular.js的嵌套属性

时间:2014-12-17 13:50:57

标签: javascript angularjs

我一直在绞尽脑汁和谷歌整个上午试图解决这个问题,但我得出结论,我需要问专家!我试图用Sinatra和Angular做嵌套属性,不要担心Sinatra方面的事情,我只是想以正确的方式将数据提供给服务器端。

请参阅下面的代码

我的输入:

<input type="text" placeholder="{{item.placeholder}}" ng-model="question.possible_answer_attributes[$index][title]" class="form-control" />

我的模型对象:

$scope.question = new Question({
  poll_id: parseInt($routeParams.id),
  title: '',
  kind: 'open',
  possible_answer_attributes: [] // I believe the issue may lie here
});

我的工厂:

 .factory('Question', function($resource) {
   return $resource('/api/questions/:id', { id: '@id' }, {
     'update'  : { method: 'PUT' },
     'get_by_poll' : { method: 'GET', url: '/api/questions_by_poll/:id', isArray: true }
   });
 })

运行保存功能时的对象:

{"poll_id"=>1, "title"=>"123123", "kind"=>"multiple", "possible_answer_attributes"=>[{"undefined"=>"412312"}, {"undefined"=>"1234124"}, {"undefined"=>"234235234"}]}

我不明白为什么我的“possible_answer_attributes”键会以“未定义”的形式出现。这可能是我错过的非常简单的事情,但任何反馈都会很棒!

提前致谢!

1 个答案:

答案 0 :(得分:0)

为了解决title属性,您需要使用字符串来索引对象:

ng-model="question.possible_answer_attributes[$index]['title']"

只要possible_answer_attributes数组看起来就是这样:

[{ title: 'my title' }]