简体   繁体   English

$ rootScope未定义

[英]$rootScope is not defined

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值可用

You missed to add $rootScope dependency 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 injection to ensure it won't break the code while doing JavaScript minification. 确保依赖注入的数组注释,以确保在进行JavaScript缩小时不会破坏代码。

Side Note:- Don't use $rootScope for sharing application common function / data, do use service/factory for the same 附注: - 不要使用$rootScope共享应用程序常用功能/数据,请使用service / factory

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
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM