AngularJS:我应该如何更新监视侦听器内已解析的promise的属性?

考虑 this Plunkr.

在我的监听器内部,我想更新已解决的承诺的属性.

>修改$$v属性的值是否正确?
>如果没有,那我该怎么办?

这是HTML:

<!DOCTYPE html>
<html id="ng-app" ng-app="myAngularapp">

  <head>
    <script data-require="angular.js@*" data-semver="1.2.0-rc2" src="http://code.angularjs.org/1.2.0-rc.2/angular.js"></script>
    <script src="script.js"></script>
  </head>

  <body ng-controller="MyController">
    <input ng-model="myDto.Weight" />{{myDto.Status}}
  </body>

</html>

这是JavaScript:

var myDto = {Weight: 200,Status: 'Acceptable'};

var myAngularapp = angular.module('myAngularapp',[]);

myAngularapp.factory('myService',function($q){
  return {
    getMyDto: function(){
      var deferred = $q.defer();
      deferred.resolve(myDto);
      return deferred.promise;
    }
  };
});

myAngularapp.controller('MyController',function MyController($scope,myService){
  $scope.myDto = myService.getMyDto();
  $scope.$watch('myDto.Weight',function(newVal,oldVal){
    if (newVal < 150) {
      $scope.myDto.$$v.Status = 'Too Light!'; // Is this the recommended way of doing it?
    }
    else if (500 < newVal) {
      $scope.myDto.$$v.Status = 'Too Heavy!';
    }
    else if (Number(newVal)) {
      $scope.myDto.$$v.Status = 'Acceptable';
    }
    else {
      $scope.myDto.$$v.Status = 'Not a number!';
    }
  });
});
我不会直接修改$$v,它是一个实现细节.相反,使用然后获得承诺的结果,然后随意使用它.这需要对代码进行最少的更改.

Demo link

myAngularapp.controller('MyController',myService){
  ($scope.myDto = myService.getMyDto()).then(function(myDto) {
    $scope.$watch('myDto.Weight',oldVal){
      if (newVal < 150) {
        myDto.Status = 'Too Light!'; // Is this the recommended way of doing it?
      }
      else if (500 < newVal) {
        myDto.Status = 'Too Heavy!';
      }
      else if (Number(newVal)) {
        myDto.Status = 'Acceptable';
      }
      else {
        myDto.Status = 'Not a number!';
      }
    });
  });
});

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...