angularjs – ui router – 嵌套视图与共享控制器

前端之家收集整理的这篇文章主要介绍了angularjs – ui router – 嵌套视图与共享控制器前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个抽象的父视图,意味着与其嵌套视图共享一个控制器。
.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'
})

路由按预期工作。

问题是,当我从一个嵌套视图更新$ scope变量时,更改不会反映在视图中。当我从父视图做同样的,它工作正常。这不是需要$ apply的情况。

我的猜想是一个新的editController实例正在为每个视图创建,但我不知道为什么或如何解决它。

这里的问题将涉及这个问题& A: 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"};
})

我们甚至可以重用这个控制器:’editController'(我们可以不必,因为$ scope.Model将在那里 – 感谢继承)

.state('edit',templateUrl: 'app/templates/editDetailsView.html',controller: 'editController'
})
.state('edit.info',templateUrl: 'app/templates/editInfoView.html',controller: 'editController'
})

现在,同一个控制器将被实例化多次(父所有子),但$ scope.Model将只启动一次(在父内部),并可用于任何地方

检查这个similar working example here

原文链接:https://www.f2er.com/angularjs/145554.html

猜你在找的Angularjs相关文章