AngularJS 在 $http 中访问 'this'
AngularJS accessing 'this' within a $http
在我的 AngularJS 服务中,我试图在 $http 成功块中的同一文件中调用方法,我必须使用 'that = 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
)
正确的做法是什么?
您可以使用粗箭头 =>
来保留 calc_total
闭包中的 this
:
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
)
参考this guide。
JavaScript ES5 等价物是
function () {}.bind(this);
粗箭头语法也进入了 ES6。
在我的 AngularJS 服务中,我试图在 $http 成功块中的同一文件中调用方法,我必须使用 'that = 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
)
正确的做法是什么?
您可以使用粗箭头 =>
来保留 calc_total
闭包中的 this
:
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
)
参考this guide。
JavaScript ES5 等价物是
function () {}.bind(this);
粗箭头语法也进入了 ES6。