我有一个抽象的父 View ,该 View 旨在与其嵌套 View 共享一个 Controller 。
.state('edit', {
abstract: true,
url: '/home/edit/:id',
templateUrl: 'app/templates/editView.html',
controller: 'editController'
})
.state('edit.details', {
url: '/details',
templateUrl: 'app/templates/editDetailsView.html'
})
.state('edit.info', {
url: '/info',
templateUrl: 'app/templates/editInfoView.html'
})
路由工作正常。
问题是,当我从其中一个嵌套 View 更新
$scope
变量时,更改未反射(reflect)在 View 中。当我从父 View 执行相同操作时,它可以正常工作。这不是需要$apply
的情况。我的猜测是为每个 View 都创建了一个新的
editController
实例,但是我不确定为什么或如何修复它。
最佳答案
这里的问题与以下问答有关:How do I share $scope data between states in angularjs ui-router?。
解决方法隐藏在:
Understanding Scopes
In AngularJS, a child scope normally prototypically inherits from its parent scope.
...Having a '.' in your models will ensure that prototypal inheritance is in play.
// So, use
<input type="text" ng-model="someObj.prop1">
// rather than
<input type="text" ng-model="prop1">.
还有这个
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.
有了我们应该在编辑 Controller 中执行此操作
controller('editController', function ($scope) {
$scope.Model = $scope.Model || {SomeProperty : "xxx"};
})
而且我们甚至可以重用该
controller: 'editController'
(我们不必这样做,因为$ scope.Model将存在-感谢继承).state('edit', {
abstract: true,
url: '/home/edit/:id',
templateUrl: 'app/templates/editView.html',
controller: 'editController'
})
.state('edit.details', {
url: '/details',
templateUrl: 'app/templates/editDetailsView.html',
controller: 'editController'
})
.state('edit.info', {
url: '/info',
templateUrl: 'app/templates/editInfoView.html',
controller: 'editController'
})
现在,同一个 Controller 将被实例化很多次(父级为所有子级),但是
$scope.Model
将仅被初始化一次(在父级内部),并且随处可见检查此similar working example here
关于angularjs - ui路由器-带有共享 Controller 的嵌套 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27768033/