AngularJS:如何使我的Controller变量在所有页面上下文中可用? [英] AngularJS : How to make my Controller variable available on all page context?

查看:35
本文介绍了AngularJS:如何使我的Controller变量在所有页面上下文中可用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与angularjs合作.在我的一个视图控制器中,我初始化了一个可变的配方数据.这是控制器:

I work with angularjs. In one of my view controller, i initialize one of my variable recipesData. Here is the controller :

(function() {
    'use strict';

    angular
        .module('myApp')
        .controller('CookController', CookController);

    CookController.$inject = ['$document','$scope','$rootScope','$window'];

    function CookController ($document,$scope,$rootScope,$window) {

        var vm = this;


        var recipesData = load();


        var viewer, ui, building;

        $scope.load = function ()  {
           var data;
           // create data 
           // ..........
            return data;
        };

    };

})();

我想使我的变量recipesData成为全局的.我有一个外部脚本,希望该变量被初始化.

I want to make my variable recipesData global. I have an external script which expects this variable initialized.

<script src="https://myexternal/lib/js/script.js"></script>

如何使其全局化或从头导入的脚本中使其可用?我的变量是从控制器初始化的.

How to make it global or make it available from script imported on head ? My variable is initialized from my controller.

谢谢

推荐答案

您可以使用 rootscope service 进行此操作,但是最好的解决方案是使用 service .这是示例服务代码,请根据您的要求进行服务.

you can do this using rootscope and using service , but best solution is using a service. Here is sample service code, make your service according to your requirement.

 fcty.service('taskService', function() {
    var task = {};
    var addTask = function(newObj) {
        task = newObj;
    }

    var getTask = function() {
        return task;
    }
    return {
        addTask: addTask,
        getTask: getTask,
    };
});

在控制器中添加 taskService

cntrl.controller('taskCreateController', function($scope, $http,taskService) {

// Add to service.

taskService.addTask($scope.data);

// Get from service in any controller by adding taskservice.

taskService.getTask();


}

此服务是根据您的要求.

This service is as per your requirement.

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

app.service('recipeService', function() {
    var recipeData = {};
     var addRecipe = function(newObj) {
        recipeData = newObj;
    }

    var getRecipe = function() {
        return recipeData;
    }
 return {
        addRecipe: addRecipe,
        getRecipe: getRecipe,
    };

});


app.controller('CookController', function($scope, $http, recipeService) {

  var vm = this;
  var viewer, ui, building;

        $scope.load = function ()  {
           var data;
           // create data 
           // ..........
            recipeService.addRecipe(data);
            return data;
        };

});

希望此示例对您有所帮助.

Hope this example is helpful to you.

这篇关于AngularJS:如何使我的Controller变量在所有页面上下文中可用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆