Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 3 从用户定义的$scope函数内部调用$resource操作_Ruby On Rails 3_Angularjs - Fatal编程技术网

Ruby on rails 3 从用户定义的$scope函数内部调用$resource操作

Ruby on rails 3 从用户定义的$scope函数内部调用$resource操作,ruby-on-rails-3,angularjs,Ruby On Rails 3,Angularjs,前端:AngularJS 1.1.5,它具有ngResource返回承诺的$then功能 后端:Rails 3.2 问题:每当我从AngJS控制器中的函数内部调用Card.update操作时,尝试记录成功和错误响应都不会得到响应。调用卡时,卡$资源的行为与预期一样。从函数外部更新操作 铁路协会 Deck has_and_belongs_to_many :cards Card has_and_belongs_to_many :decks resources :cards do get '/d

前端:
AngularJS 1.1.5
,它具有
ngResource
返回承诺的
$then
功能
后端:
Rails 3.2

问题:每当我从AngJS控制器中的函数内部调用
Card.update
操作时,尝试记录
成功
错误
响应都不会得到响应。调用
卡时,
$资源的行为与预期一样。从函数外部更新
操作

铁路协会

Deck has_and_belongs_to_many :cards
Card has_and_belongs_to_many :decks
resources :cards do
  get '/decks' => 'cards#decks', on: :member
end
铁路线路

Deck has_and_belongs_to_many :cards
Card has_and_belongs_to_many :decks
resources :cards do
  get '/decks' => 'cards#decks', on: :member
end
Rails卡控制器“更新”操作

def update
  @card = Card.where( id: params[:id] ).first

  unless params[:deck_id].nil?
    @deck = Deck.where( id: params[:deck_id] ).first

    @deck.cards << @card
  end

  render json: Card.update( params[:id], params[:card] )
end
卡片更新功能(在AngJS控制器内部):(成功/错误消息不会记录到控制台)

介绍 我解决了自己的问题。我用Misko Hevery的这个作为参考

我的PUT请求未执行的原因: 显然,在Angular 1.1.x中,如果您离开Angular执行上下文,您将超出Angular的
$scope.$apply
函数。在我的例子中,我使用JQuery UI的
可排序
功能-每当
卡片
放在新的
卡片组
中时,我都想更新
卡片组的
以反映更新

据我所知,正因为如此,我在角度执行上下文之外
ngResource
不会执行
PUT
语句,Angular的
promise
对象的
$then
函数将永远不会被调用

解决方案: 只需将
$scope.$apply
函数包装在
卡周围。更新
操作允许执行该操作,随后允许执行
$then
函数。请参阅下面的代码示例以了解进一步的说明:

$scope.$apply ->
  Card.update(
    id: 1
    deck_id: 2
    front: "HELLO WORLD!"
  ).$then ((success) ->
    console.log "Success"
    console.log success
  ), (error) ->
    console.log "Error"
    console.log error

另外,请注意,$then函数接受一个success and error回调函数,而不是一个带有success and error参数的函数。