Angular 具有服务的父子范围

Angular parent child scope with service

我对 Angular 的一些概念感到困惑,尤其是变量和作用域的流动。

我想做的是在子控制器中设置一个变量并将其传递给父范围。考虑这个简单的例子:

module.controller('childController', childController);
function childController($scope,$http,$window, hexafy) {
    $scope.hex = hexafy.myFunc(17);      
}

module.controller('parentController', parentController);
function parentController($scope, hexafy) {

}

module.service('hexafy', function() {
    this.myFunc = function (x) {
        return x.toString(16);
    }
});

那么我的加价如下:

{{hex}}

<section data-ng-controller="listingsViewController">....</section>

计算由子控制器处理,但如您所见,我想将变量传递给 'parent'。我已阅读有关 'parent' 范围的信息,但我知道这不是最佳做法,因此我正在尝试使用服务。我哪里错了?

您应该首先在子控制器中使用服务函数设置值,然后在父控制器中使用父控制器中的 getvalue 函数。

您的 setvalue 和 getvalue 函数应该可用。

控制器代码

app.controller('childController', childController);
function childController($scope,$http,$window, hexafy) {
    $scope.childValue = "Value in child controller"
    hexafy.setValue($scope.childValue);      
}

app.controller('parentController', parentController);
function parentController($scope, hexafy) {
  $scope.parentValue = hexafy.getValue()
}

服务代码

app.service('hexafy', function() {

  var value = "";
  this.setValue = function(val) {
    value = val
  },

  this.getValue = function() {
    return value;
  }


    this.myFunc = function (x) {
        return x.toString(16);
    }
});

Html代码

<div ng-controller="childController">
      <h2>Child controller</h2>
      {{childValue}}

    </div>

     <div ng-controller="parentController">
       <h2>Parent controller</h2>
      {{parentValue}}

    </div>

看看工作plunker

有很多不同的方法可以实现这一点,我实际上推荐以下方法(在父控制器和子控制器中使用通用的 $scope object variable)而不是使用服务,因为它更容易和更清晰的方法。

然后您可以使用 $scope.shareValue.hex 在父控制器中访问 hex 值。

module.controller('childController', childController);
function childController($scope,$http,$window, hexafy) {
    $scope.shareValue.hex = hexafy.myFunc(17);
}

module.controller('parentController', parentController);
function parentController($scope, hexafy) {
    var shareValue = {
       hex: ''
    };
    $scope.shareValue = shareValue;
}

============================================= ========================= 使用服务更新:
请参考下面评论中的 Matthew Cawley post。