$ watch仅在重新加载时触发

时间:2016-09-01 14:40:10

标签: angularjs coffeescript ngroute

我有一个包含3个部分的页面。我使用的是ui-router,我使用抽象视图来获取车辆对象。 在第二个视图中,我需要根据车辆对象计算一个字段,我使用$ scope。$ watch。 我遇到的问题是当状态变为“dashboard.home.vehicle_wizard.proof”时#39; watch方法被调用一次,但是车辆未定义,并且它不会被第二次击中。如果我重新加载页面,它就会被击中。

任何想法?

  .state 'dashboard.home.vehicle_wizard',
      url: "vehicle"
      templateUrl: 'views/vehicle-wizard.html'
      controller: 'VehicleWizardCtrl'
      abstract: true

  .state 'dashboard.home.vehicle_wizard.info',
      url: "/info"
      templateUrl: 'views/vehicle-info.html'
      controller: 'VehicleInfoCtrl'

  .state 'dashboard.home.vehicle_wizard.proof',
      url: "/proof"
      templateUrl: 'views/vehicle-proof.html'
      controller: 'VehicleProofCtrl'

VehicleWizardCtrl:

angular.module 'App'
.controller 'VehicleWizardCtrl', ($scope, $state, vehicle) ->

    vehicle.get().then (result) ->
      if result
        $scope.vehicle = result[result.length - 1]

VehicleInfoCtrl:

$scope.submit = ->
  return if !$scope.form.$valid
  $scope.loading = true
  $scope.vehicle.status = "confirmed"
  $scope.vehicle.update()
  .then (vehicle) ->
    $scope.loading = false
    $scope.vehicle = vehicle
    $state.go "dashboard.home.vehicle_wizard.proof", $scope.vehicle
  , (resp, headers) ->
    $scope.loading = false
    _.each resp.data, (errors, key) ->
      if $scope.form[key]
        $scope.server_errors[key] = errors[0]
        $scope.form[key].$error["server"] = errors[0]
        $scope.form[key].$setValidity('server', false)

VehicleProofCtrl:

$scope.$watch('vehicle', (newValue, oldValue)->
  if ($scope.vehicle)
    $scope.vehicle.age = parseInt(moment($scope.vehicle.regDate, "YYYY-MM-DD").fromNow(true).match(/\d+/g))
)

2 个答案:

答案 0 :(得分:1)

使用$watchCollection

$watch内容

$watchCollection监视对象的属性,并在任何属性发生更改时触发(对于数组项和对象映射,这意味着要查看属性)。如果检测到更改,则会触发侦听器回调。

了解更多信息read doc

答案 1 :(得分:0)

您需要为对象执行deepwatch,并且可以通过将true作为第3个参数传递来完成:

$scope.$watch('vehicle', (newValue, oldValue)->
  if ($scope.vehicle)
    $scope.vehicle.age = parseInt(moment($scope.vehicle.regDate, "YYYY-MM-DD").fromNow(true).match(/\d+/g))
, true)