AngularJS$scope继承服务

AngularJS $scope inheritance service

本文关键字:服务 继承 scope AngularJS      更新时间:2023-09-26

我的代码遇到了一些问题。我无法传递或控制台.log数据服务中继承的 $scope.user。由于我在另一种看起来相同的情况下也遇到了这个问题,我想这是因为回调。

主控制器创建用户

 .controller('mainCtrl', function ($scope, dataService) {
    dataService.getUser(function (response) {
        $scope.user = response.data[0];
    })

数据服务

    .service('dataService', function ($http) {
    this.getUser = function (callback) {
        $http.get('mock/user.json')
            .then(callback)
    };

导航控制器(主 Ctrl 的子控制器(:

    .controller('navCtrl', function ($scope, dataService) {
    //$scope.user = "test";
    console.log ($scope.user);
    dataService.getNavItems($scope.user,function (response) {
        $scope.navItems = response.data;
    });

正如您可以猜到的那样,如果我手动设置$scope.user,它就可以正常工作。

实例

化 navCtrl 时,承诺尚未解决。你可以做的是从 $http.get 返回承诺,而不是直接在回调中设置 scope.user。 然后只需将调用 getNavItems 包装在承诺中即可。

这是假设,navCtrl 是 MainCtrl 的子级

.service('dataService', function ($http) {
  this.getUser = function () {
    return $http.get('mock/user.json');
  }};
.controller('mainCtrl', function ($scope, dataService) {
    $scope.userPromise = dataService.getUser();
 })
.controller('navCtrl', function ($scope, dataService) {
  $scope.userPromise.then(function(response) {
   var user = response.data[0];
   dataService.getNavItems(user, function (response) {
       $scope.navItems = response.data;
   });
});

}(

两个控制器的作用域将不同,因此,如果您在另一个控制器中定义它,则不会在一个控制器中定义它。如果您希望它在两者中工作,只需使用数据服务。

 .service('dataService', function ($http) {
    this.getUser = function () {
       $http.get('mock/user.json').then(function(data) {
          this.user = data;
       )}
};

然后在每个控制器中分别访问它,它将可供两个控制器使用。

似乎控制器"mainCtrl"和"navCtrl"具有不同的作用域。如果"navCtrl"的作用域是"mainCtrl"作用域的子作用域,则可以使用$scope.$parent.user

在解析承诺时触发日志记录 $scope.$parent.$watch('user', fucntion(newVal){console.log(newVal)})

如果没有,我建议有某种上下文,您将在其中存储不同控制器使用的数据。

查找范围,甚至可以在浏览器控制台中使用angular.element('[ng-controller="mainCtrl"]').scope()