javascript - 在 $http 之后更新多个 Controller 中的范围

标签 javascript angularjs angularjs-scope

我正在努力弄清楚如何做到这一点。希望有人能帮忙:)

  1. 我的 Angular 应用程序中有多个 Controller 。就像 titleCtrl 和 SettingsCtrl

  2. 我有一个包含如下变量的服务:

    var myVar = {title: 'test', settings: {color: 'black', font: 'verdana'}};

  3. 我正在发出 $http.get 请求以从服务器更新“myVar”变量。

问题是,http请求完成后如何更新titleCtrl中的$scope.title和SettingsCtrl中的$scope.settings?我知道如何在单个 Controller 中执行此操作,但如何更新多个 Controller 中的 $scopes ?

最佳答案

在服务中使用该变量的监视。更新后,然后更新 Controller 范围中的值。这是一个例子:

在 Controller 内,您可以在 YourService 上监视 var myVar,当它发生变化时,用它的值更新名为 myVarInController 的变量更改为。

$scope.$watch(
    // This function returns the value being watched.
    function() { 
        return YourService.myVar; 
    },
    // This is the change listener, called when the value returned above changes
    function(newValue, oldValue) {
        if ( newValue !== oldValue ) {
            $scope.myVarInController = newValue;
        }
    }
);

关于javascript - 在 $http 之后更新多个 Controller 中的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25665336/

相关文章:

javascript - 为什么 Angular js 在这里不起作用

javascript - angularJS 将对象属性传递给模态

javascript - AngularJS 如何使用 ng-repeat $compile 元素?

javascript - 如果我可以使用 $scope.$root,为什么还要使用 $rootScope?

javascript - 如何从 `$scope` Controller 更新 `directive` 对象

c# - 在 iframe 中显示 aspx,aspx 显示 pdf

javascript - D3 鼠标悬停在本地主机上很好,但在部署站点上却不行

javascript - 将图像复制到剪贴板

php 中的 Javascript 函数不起作用

javascript - Angularjs 如何将选中的复选框的值发送到 .php?