Angularjs 在范围更改时从工厂获取值

Angualrjs get value from factory when scope change

我有一个工厂用于获取有条件的数据。我想要的是当条件改变时工厂也需要更新。

$scope.format=1;    
homefact.get_download_format($scope.format).then(function (response) {
        $scope.download = response;
  });

//watch scople format
  $scope.$watch("format", function (newValue, oldValue) {
        if ($scope.format === 1) {
         //recall the get_donwload_format here with new value

        } else {
            //recall the get_donwload_format here with new value
        }
    });

谢谢!

围绕一个函数包装服务并在监视函数中调用它

$scope.format=1;    
callDownload($scope.format);

function callDownload(newValue){
 homefact.get_download_format(newValue).then(function (response) {
    $scope.download = response;
 });
}

$scope.$watch("format", function (newValue, oldValue) {
        if ($scope.format === 1) {
         callDownload(newValue)

        } else {
            //recall the get_donwload_format here with new value
        }
});

我看不到 if/else 的用法,因为您想在 $scope.format 发生变化时使用 newValue 调用服务方法。

所以可以这样做:

  $scope.format=1;    
  homefact.get_download_format($scope.format).then(function (response) {
        $scope.download = response;
   });

  //watch scople format
  $scope.$watch("format", function (newValue, oldValue) {
    if(newValue != oldValue && newValue) {
      homefact.get_download_format(newValue).then(function (response) {
           $scope.download = response;
      });
    }
  });