angularjs - 更新服务内的范围值

标签 angularjs service factory

我的应用程序中有以下 Controller :

主 Controller :

app.controller('AppCtrl', ['$scope', function ($scope) {
    $scope.app = {
        amount: 0
    };
}]);

子 Controller :

app.controller('ChildCtrl', ['$scope', function ($scope) {
    var timeLoop = function (amount) {
        $timeout(function () {
            $scope.app.amount++;

            if($scope.app.amount < amount) {
                timeLoop(amount);
            }
        }, 10);
    }
    timeLoop(20);
}]);

另一个子 Controller :

app.controller('AnotherChildCtrl', ['$scope', function ($scope) {
    var timeLoop = function (amount) {
        $timeout(function () {
            $scope.app.amount++;

            if($scope.app.amount < amount) {
                timeLoop(amount);
            }
        }, 10);
    }
    timeLoop(100);
}]);

如何对服务做同样的事情?我不想在 MainCtrl 中使用 timeLoop 函数。你知道我该怎么做吗?

最佳答案

您的主 Controller :

app.controller('AppCtrl', ['$scope','timeOutService', function ($scope,timeOutService) {
    $scope.app = {
        amount: timeOutService.amount 
    };
}]);

您可以拥有这样的通用服务:

app.service('timeOutService', function($timeout) {
    this.amount = 0;
    this.timeLoop = function (amount) {
        var that = this;
        $timeout(function () {
            that.amount++;

            if(that.amount < amount) {
                that.timeLoop(amount);
            }
        }, 10);
    }
});

并且在您的多个 Controller 中,您可以注入(inject)相同的内容:

子 Controller :

app.controller('ChildCtrl', ['$scope','timeOutService', function ($scope,timeOutService) {     console.log("timeOutService", timeOutService);
    timeOutService.timeLoop(20);
}]);

另一个子 Controller :

app.controller('AnotherChildCtrl', ['$scope','timeOutService', function ($scope,timeOutService) { 
    timeOutService.timeLoop(20);
}]);

下面是一个工作 fiddle : https://jsfiddle.net/40zodv7b/

关于angularjs - 更新服务内的范围值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40356671/

相关文章:

javascript - Angularjs 应用程序未使用 ui-router 路由回主页

javascript - JavaScript 跨各种 IDE 的代码格式化标准

service - Symfony 4 参数没有类型提示,你应该明确配置它的值

android - Ionic Android apk 无法访问互联网

c# - WCF 到数据库连接

c# - 使用 C# ServiceController 和模拟启动/停止 Windows 服务

android - 系统在出厂重置和系统更新期间是否广播任何 Intent ?

java - 使用服务作为 "Factory"返回不同的 Bean 实现

Java工厂模式-如何防止匿名子类

javascript - 在第一个条目后隐藏占位符