$ emit和$ broadcast替代不存在的控制器

时间:2016-01-31 16:34:27

标签: angularjs

我遇到过这样一种情况:我使用的angular插件只允许在运行时在其控制器本身的$ scope上进行语言更改。

我在这里遇到的问题是,在视图切换之前,某些控制器将不存在,但我需要确保在更改标题中的语言时切换插件的语言。

总结:
如何向不存在的控制器发射和广播(控制器仅在视图切换后可用)。请注意,ChildAController,ChildBController,..,ChildZController是独立的视图。

angular.module('parent').controller('HeaderController', function($scope) {
    $scope.changeLanguage = function (language) {
        // trigger $scope.changePluginLanguage in every controller
        // where ChildAController and ChildBController is of different view (and non-existent at the time)
    }
}

angular.module('childA').controller('ChildAController', function($scope, CustomPlugin) {
    $scope.changePluginLanguage = function(language) {
        $scope.pluginOptions.LanguageUrl = language + ".json";
    }
}

angular.module('childB').controller('ChildBController', function($scope, CustomPlugin) {
    $scope.changePluginLanguage = function(language) {
        $scope.pluginOptions.LanguageUrl = language + ".json";
    }
}

...
...

angular.module('childZ').controller('ChildZController', function($scope, CustomPlugin) {
    $scope.changePluginLanguage = function(language) {
        $scope.pluginOptions.LanguageUrl = language + ".json";
    }
}

视图

<!DOCTYPE html>
<html ng-app="app">
    <head></head>
    <body>
        <div ng-controller="HeaderController">
            <select ng-click="changeLanguage">
                <option ng-click="changeLanguage('English')">English</option>
                <option ng-click="changeLanguage('Spanish')">Spanish</option>
            </select>
        </div>
        <div ui-view></div>
    </body>
</html>

// View A
<div ng-controller="ChildAController">
    <CustomPlugin pluginOptions="pluginOptions"></CustomPlugin>
</div>

// View B
<div ng-controller="ChildBController">
    <CustomPlugin pluginOptions="pluginOptions"></CustomPlugin>
</div>

1 个答案:

答案 0 :(得分:0)

  

$ emit和$ broadcast alternative

使用$watch服务保存当前语言的值。

客户端控制器

angular.module('childA').controller('ChildAController', function($scope, MyService) {
    $scope.$watch(MyService.languageGet, function (language) {
        $scope.pluginOptions.LanguageUrl = language + ".json";
    }
}

工厂服务

angular.module("myApp").factory("MyService", function() {
    var language = "default";
    function getLanguage() {
        return language;
    };
    function setLanguage(value) {
        language = value;
        return value;
    };
    return { getLanguage: getLanguage,
             setLanguage: setLanguage
    };
});

在父控制器(或任何控制器)中,您可以设置语言。

MyService.setLanguage(newLanguage);

当实例化客户端控制器时,$watch将设置语言,然后在每个摘要周期,它将检查语言设置并在必要时进行更新。

有关$watch的详细信息,请参阅AngularJS $rootScope.scope API Reference -- $watch