AngularJS получает доступ к 'this' в пределах $ http

0

В моей службе AngularJS я пытаюсь вызвать метод в том же файле в блоке успеха $ http, и я должен использовать 'this = this', чтобы я мог получить доступ к нему должным образом.

calc_total: (line) ->
  that = this
  $http.get("/item/get_cost?costing_id=" + line.costing_id).then (
    (response) ->
      # If successful set the cost per unit cents
      line.cost_cents = response.data['cost_cents']
      that.accumulated_balance(line) # Update balance
  )

Каков правильный способ сделать это?

Теги:
coffeescript

1 ответ

1
Лучший ответ

Вы можете использовать жир arrow => чтобы сохранить this от закрытия calc_total:

calc_total: (line) ->
  $http.get("/item/get_cost?costing_id=" + line.costing_id).then (
    (response) =>
      # If successful set the cost per unit cents
      line.cost_cents = response.data['cost_cents']
      this.accumulated_balance(line) # Update balance
  )

См. Это руководство для справки.

Эквивалент JavaScript ES5

function () {}.bind(this);

Синтаксис толстой стрелки пробился и в ES6.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню