【问题标题】:Immediately invoke function and call in $scope立即调用函数并调用 $scope
【发布时间】:2016-08-11 11:35:14
【问题描述】:

我正忙于开发一个从 API 获取数据的 AngularJS 应用程序。但是我想知道是否有可能直接调用范围内的函数并正常调用它。

这就是我的控制器中的内容:

var self = this;
$scope.refreshData = (function() {
    $http({
            method: 'GET',
            url: './test-api/testdata.php'
        })
        .success(function(data) {
            self.apiData = data;
        });
    console.log('Refresh executed');
})();

$interval(function() {
    console.log('Refresh called');
    $scope.refreshData();
}, 60000);

此日志:

Refresh executed
angular.js:13540 TypeError: $scope.refreshData is not a function

我知道我可以将其更改为普通函数并使用 $scope.refreshData() 调用它,但我只是想知道 AngularJS 中是否有方法。

【问题讨论】:

  • 这里的javascript规则是一样的!

标签: javascript angularjs iife


【解决方案1】:

这里的$scope.refreshData 是未定义的,因为您分配给它的值是IIFE 返回的值。为此,您应该执行以下操作:

var self = this;
($scope.refreshData = function() {
    $http({
            method: 'GET',
            url: './test-api/testdata.php'
        })
        .success(function(data) {
            self.apiData = data;
        });
    console.log('Refresh executed');
})(); 

$interval(function() {
    $scope.refreshData();
    console.log('Refresh called');
}, 60000);

PS:你可以阅读更多关于它的信息here

【讨论】:

  • 阅读我的问题的最后一句话。我知道可以这样做,但我想知道我是否可以在加载时直接调用它并稍后调用它(在我的示例中是间隔)
  • 是的,我明白了,也适合我。从未想过将( 放在$scope 之前。
猜你喜欢
  • 2010-10-30
  • 1970-01-01
  • 2020-01-02
  • 2012-06-14
  • 2016-04-07
  • 1970-01-01
  • 2012-03-31
相关资源
最近更新 更多