gpt4 book ai didi

angularjs - ui路由器-带有共享 Controller 的嵌套 View

转载 作者:行者123 更新时间:2023-12-03 08:47:08 24 4
gpt4 key购买 nike

我有一个抽象的父 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com