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

标签 angularjs angular-ui-router

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

相关文章:

javascript - AngularJS - Controller 初始化时触发的 ng-change

javascript - Angular 对象如何获取另一个对象的值

javascript - $state.go 从我当前的状态到当前的状态是否会触发相关事件?

javascript - 与 ui-sref 的链接不显示正确的 css

javascript - 使用 angularjs 渲染星级评分系统

javascript - 在 AngularJS Controller 中获取 $resource 调用的值

javascript - 从对象数组初始化时使用angularjs在SELECT下拉列表中选择特定项目

javascript - Angularjs 和 ui-router 的复杂状态

javascript - transitionTo 的 UI 路由器问题

javascript - 类型错误 : Cannot read property 'go' of undefined