【问题标题】:Angualrjs get value from factory when scope change当范围改变时,Angularjs 从工厂获取价值
【发布时间】:2017-05-30 08:03:56
【问题描述】:

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

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

谢谢!

【问题讨论】:

  • 在你想要的两个地方//用新值调用这里的get_donwload_format..,那为什么是if/else?
  • 哈哈明白了。谢谢人

标签: angularjs factory watch


【解决方案1】:

我看不到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;
      });
    }
  });

【讨论】:

  • 您的回答很好,但我们需要复制并粘贴整个 get_downlaod_format 函数。不是个好主意。
  • IMO 这只是一个调用并在某一点使用,所以没关系.. 但如果在多个地方使用,则将其包装在另一个函数中。
【解决方案2】:

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

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

【讨论】:

  • @Vuong Tran 不错。如果这有帮助,请务必检查答案:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-08
  • 2016-01-25
  • 1970-01-01
相关资源
最近更新 更多