我需要子状态能够使用父状态的解析函数。但我还需要为两种状态保持相同的 ui-view。这是一个 fiddle .还有一个代码
$stateProvider
.state('parent', {
url: "/",
template: '<p>Hello {{parent.one}}</p><br>'
+ '<button ng-click="goToChild()">child</button><br>',
// this one below work but I don't need it
// template: '<p>Hello {{parent.one}}</p><br>'
// + '<button ng-click="goToChild()">child</button><br>'
// + '<div ui-view></div>',
resolve: {
test: function() {
return 1;
}
},
controller: function($scope, $state, test) {
$scope.parent = { one: test };
$scope.goToChild = function() {
$state.go('parent.child');
}
}
})
.state('parent.child', {
url: "/child",
template: '<p>Hello {{child.one}}</p>',
controller: function($scope, test) {
$scope.child = { one: test };
}
})
$urlRouterProvider.otherwise('/');
最佳答案
答案应该隐藏/显示在这两个状态的定义中:
多视角父级
.state('parent', {
url: "/",
views: {
'@': {
template: '<div ui-view=""></div>',
controller: function($scope, $state, test) {
$scope.parent = { one: test };
$scope.goToChild = function() {
$state.go('parent.child');
}
}
},
'@parent': {
template: '<p>Parent says: hello <pre>{{parent | json}}</pre></p>'
+ '<br><button ng-click="goToChild()">child</button><br>',
}
},
resolve: {
test: function() { return 1; },
},
})
child 消耗 parent 的决心,并拥有自己的决心
.state('parent.child', {
url: "^/child/:id",
template: '<p>Child says: hello <pre>{{child | json }}</pre></p>',
resolve: {
testChild: function() { return 2; },
},
controller: function($scope, test, testChild) {
$scope.child = {
one: test,
two : testChild,
parent: $scope.parent,
};
},
})
查一下here
它是如何运作的?好吧,这一切都基于:
Scope Inheritance by View Hierarchy Only
Keep in mind that scope properties only inherit down the state chain if the views of your states are nested. Inheritance of scope properties has nothing to do with the nesting of your states and everything to do with the nesting of your views (templates).
It is entirely possible that you have nested states whose templates populate ui-views at various non-nested locations within your site. In this scenario you cannot expect to access the scope variables of parent state views within the views of children states.
还有:
View Names - Relative vs. Absolute Names
Behind the scenes, every view gets assigned an absolute name that follows a scheme of
viewname@statename
, where viewname is the name used in the view directive and state name is the state's absolute name, e.g. contact.item. You can also choose to write your view names in the absolute syntax.For example, the previous example could also be written as:
.state('report',{
views: {
'filters@': { },
'tabledata@': { },
'graph@': { }
}
})
因此,上述文档引用是 plunker 的核心.父级使用多个 View ,其中一个未命名 - 并将用于继承。 Parent 还将其自己的“父” View 注入(inject)该 View 。 parent 的决心已经到位......
子级现在注入(inject)其父级的 anchor ,父级确实拥有所需的所有内容。这意味着,那个 child 确实继承了范围并解决了问题。它也表明了自己的决心......
关于javascript - Angular ui 路由器 : keep same ui-view for child,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27586546/