如何 get/set controller/module 之外的变量?

how to get/set variables outside of controller/module?

假设我有一个预定义的 module/controller,它将苹果设置为绿色。

var _core = angular.module('_core', []);
_core.controller('mainController', function($scope, $controller, $http) {
    $scope.apple = 'green';
});

我可以把苹果拿出来吗?有点像。

_core.mainController.apple

这可能吗?我还需要用外部插件设置变量,对不起,我是一个完整的 angular 菜鸟,有点令人生畏。

如果您希望值可以在控制器外部访问,那么您可以将其存储在 $rootScope 而不是 $scope 中,并且您可以直接使用存储在 $rootScope 中的可注入值.所以代码变成:

var _core = angular.module('_core', []);
_core.controller('mainController', function($scope, $controller, $http, $rootScope) {
    $rootScope.apple = 'green';
});

现在在别的地方说工厂,你可以把它当作:

var _core1 = angular.module('_core1', []);
_core1.factory('someFactory', function($scope, $rootScope, $http) {
  var fruit = $rootScope.apple;
//variable fruit now contains green
});

您可以使用工厂来设置控制器外的任何模块。

    var App = angular.module('app', []);

    App.factory('messages', function () {
         var messages = {};

         messages.list = [];

        messages.add = function (someString) {
            messages.list.push(someString);
        };
    messages.get = function() {

};
        messages.clearList = function () {
            messages.list.length = 0;
        }

        return messages;
    });

并且您可以将此服务方法调用到您的控制器中。

App.Controller('myController',['$scope', 'messages', function(scope, messages) {
        messages.add('Hello');
        var myListy = messages.get();
   }]);