我有一个父状态:
.state('contact', {
url: '...',
templateUrl: '...',
controller: function ($scope) {
$scope.object.property = ['item1', 'item2', 'item3']
}
})
及其子元素:
.state('contact.list', {
url: '...',
templateUrl: '...',
controller: function ($scope) {
var parentObj = $scope.$parent.object.property[1];
})
如您所见,状态 'contact.list'
是状态 'contact'
的子级,因此 'contact.list'
有一个子作用域。我使用变量 parentObj
来存储对 parent 中对象的引用,$scope.object.property
。
无论如何,我想做的是将项目添加到子范围中的范围,并将它们添加到父范围中的对象< em>范围。
例如,如果可能的话,能够向子对象添加一些属性会很酷:
.state('contact.list', {
url: '...',
templateUrl: '...',
controller: function ($scope) {
var parentObj = $scope.$parent.object.property[1];
$scope.parentObj.newProperty = 'im a new property!';
})
并将其添加到父 Controller ,然后父 Controller 的最佳范围具有:
$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!';
})
对于我尝试发送给家长的每一个项目。家长。如果有任何方法可以实现这一目标,任何建议将不胜感激。
最佳答案
我想说,这可以很容易实现。只需在父 $scope 中创建一个引用对象..一切都会按预期工作
.state('contact', {
url: '...',
templateUrl: '...',
controller: function ($scope) {
$scope.Model = {};
}
})
有a working example ,与此问答相关:
Destroy scope before change path in ui-router
状态定义:
.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) {}])
关于javascript - AngularJS 使用子 $state Controller 向父级范围内的对象添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30321803/