加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 08:36:04 所属栏目:安全 来源:网络整理
导读:我有一个抽象的父视图,意味着与其嵌套视图共享一个控制器。 .state('edit',{ abstract: true,url: '/home/edit/:id',templateUrl: 'app/templates/editView.html',controller: 'editController'}).state('edit.details',{ url: '/details',templateUrl: 'ap
我有一个抽象的父视图,意味着与其嵌套视图共享一个控制器。
.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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读