AngularJS 使用 child $state 控制器向 objects 添加属性到 parent 的范围

AngularJS using child $state controllers to add properties to objects on a parent's scope

我有一个 parent 状态:

.state('contact', {
  url: '...',
  templateUrl: '...',
      controller: function ($scope) {
      $scope.object.property = ['item1', 'item2', 'item3']
  }
})

及其child:

.state('contact.list', {
  url: '...',
  templateUrl: '...', 
  controller: function ($scope) {
    var parentObj = $scope.$parent.object.property[1];
  })

如您所见,状态 'contact.list' 是状态 'contact'child,因此 'contact.list'有一个 child 范围。我正在使用变量 parentObjparent$scope.object.property 中存储对 object 的引用。

无论如何,我想做的是将项目添加到 child scope 中的 scope,并将它们添加到 parent 范围 中的 object。

例如,如果可能的话,能够向 child object 添加一些属性会很酷:

.state('contact.list', {
  url: '...',
  templateUrl: '...', 
  controller: function ($scope) {
    var parentObj = $scope.$parent.object.property[1];
    $scope.parentObj.newProperty = 'im a new property!';
  }) 

并将其添加到 parent 控制器中,然后控制器的最佳作用域将具有:

$scope.object.property[1].newProperty

不幸的是,据我所知,不可能以这种方式引用 $parent scopes,我不想去声明:

.state('contact.list', {
  url: '...',
  templateUrl: '...', 
  controller: function ($scope) {
    $scope.$parent.object.property[1].newProperty = 'im a new property!';
    $scope.$parent.object.property[1].secondNewProperty = 'im the second new property!';
    $scope.$parent.object.property[1].thirdNewProperty = 'im the third new property!';
  }) 

对于我尝试发送到 parent 的每一个项目。如果有任何方法可以实现这一点,将不胜感激任何建议。

我想说,这真的很容易实现。只需在父级 $scope 中创建一个引用对象.. 一切都会按预期工作

.state('contact', {
  url: '...',
  templateUrl: '...',
      controller: function ($scope) {
        $scope.Model = {};
  }
})

a working example,与本问答相关:

状态定义:

.controller('ParentCtrl', ['$scope', function ($scope) { 
  $scope.Model = {
    SharedName: "This is shared name",
  }
  $scope.NotSharedName = $scope.NotSharedName 
                      || "This name is cloned, but then lives its own way";
}])
.controller('ChildCtrl', ['$scope', function ($scope) {}])