Javascript $rootScope 未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29396919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:17:50  来源:igfitidea点击:

$rootScope is not defined

javascriptangularjscookiesdependency-injection

提问by Darren Sweeney

I'm trying to use a cookie value in multiple places and within multiple controllers but I get error saying $rootScope is not defined

我试图在多个地方和多个控制器中使用 cookie 值,但我收到错误消息,说$rootScope 未定义

Here's the code:

这是代码:

capApp.controller('cookieCtrl', ['$scope','$cookies', function($scope, $rootScope, $cookies) {
  // set variable for nav
  $rootScope.cookieSet = $cookies.user_id;
}]);

capApp.controller('mainController', function($scope, $location) {  
  $scope.user_id = $rootScope.cookieSet; // set global var
});

Is there a better way to do this? Basically I want the cookie value available site wide

有一个更好的方法吗?基本上我希望 cookie 值在整个站点范围内可用

回答by Pankaj Parkar

You missed to add $rootScopedependency in both controllers

您错过了$rootScope两个控制器中添加依赖项

Code

代码

capApp.controller('cookieCtrl', ['$scope','$rootScope', '$cookies', 
  function($scope, $rootScope, $cookies) {
  // set variable for nav
  $rootScope.cookieSet = $cookies.user_id;
}]);

capApp.controller('mainController', ['$scope', '$location', '$rootScope', 
  function($scope, $location, $rootScope) {  
  $scope.user_id = $rootScope.cookieSet; // set global var
});

Ensure array annotation of dependency injectionto ensure it won't break the code while doing JavaScript minification.

确保依赖注入的数组注释以确保它在进行 JavaScript 缩小时不会破坏代码。

Side Note:- Don't use $rootScopefor sharing application common function / data, do use service/factory for the same

边注:-不要$rootScope用于共享应用程序公共功能/数据,请使用服务/工厂

回答by squiroid

You didn't inject $rootScope in mainController

你没有在 mainController 中注入 $rootScope

capApp.controller('mainController', function($scope,$rootScope, $location) {  
  $scope.user_id = $rootScope.cookieSet; // set global var
});

Update:

更新:

First create a service that acts like a bridge between controllers:

首先创建一个充当控制器之间桥梁的服务:

1) addCookie used to add cookieset.

1) addCookie 用于添加cookieset。

2) getCookie used to get cookieset.

2) getCookie 用于获取cookieset。

capApp.factory('user', function() {
  var cookieSet;

  var addCookie = function(val) {
      cookieSet=val;
  }

  var getCookie = function(){
      return cookieSet;
  }

  return {
    addCookie : addCookie,
    getCookie : getCookie 
  };

});

capApp.controller('cookieCtrl', ['$scope', 'user', '$cookies', function($scope, user, $cookies) {
  // set variable for nav
  user.addCookie($cookies.user_id);
}]);

capApp.controller('mainController', function($scope, $location,user) {  
  $scope.user_id =user.getCookie(); // set global var
});