当范围变化时,Angualrjs从工厂获得价值

时间:2017-05-30 08:03:56

标签: angularjs factory watch

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

$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
        }
    });

谢谢!

2 个答案:

答案 0 :(得分:2)

我没有看到if/else的使用,因为每当newValue更改时,您都希望使用$scope.format调用服务方法。

所以可以这样做:

  $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;
      });
    }
  });

答案 1 :(得分:1)

围绕函数包装服务并在监视函数

中调用它
$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
        }
});