Angular-ui.router:在没有视图刷新的情况下更新 URL [英] Angular-ui.router: Update URL without view refresh

查看:21
本文介绍了Angular-ui.router:在没有视图刷新的情况下更新 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Angular SPA,它提供了各种推荐列表和一个谷歌位置地图,基于一些餐厅数据的不同切割(参见 m.amsterdamfoodie.nl).我希望这些列表中的每一个都有自己的 URL.为了让 Google 抓取不同的列表,我使用 标签进行画布导航.

目前 标签会导致视图刷新,这在地图上非常明显.

因此,我的问题是如何更新模型和 URL,但不刷新视图?(另请参见 Angular/UI-Router - 如何在不刷新所有内容的情况下更新 URL?)

我尝试了很多方法,目前有这个 html

<a href="criteria/price/1" class="btn btn-default" ng-click="main.action($event)">预算</a>

在控制器中:

this.action = ($event) ->$event.preventDefault()参数 = $event.target.href.match(/criteria\/(.*)\/(.*)$/)# 似乎导致视图刷新# history.pushState({}, "page 2", "criteria/"+params[1]+"/"+params[2]);# 似乎导致视图刷新# $state.transitionTo 'criteria', {criteria:params[1], q:params[2]}, {inherit:false}更新模型(...)

而且,我认为正在发生的是我正在触发 $stateProvider 代码:

angular.module 'afmnewApp'.config ($stateProvider) ->$stateProvider.state 'main',网址:'/'templateUrl: 'app/main/main.html'控制器:'MainCtrl'控制器为:'主要'.state '标准',url: '/criteria/:criteria/:q'templateUrl: 'app/main/main.html'控制器:'MainCtrl'控制器为:'主要'

一个可能的线索是,如果我加载例如下面的代码http://afmnew.herokuapp.com/criteria/cuisine/italian 然后是视图在您导航时刷新,而如果我加载 http://afmnew.herokuapp.com/ 则没有刷新,但没有 URL 更新.我完全不明白为什么会这样.

解决方案

基于我们之前的讨论,我想给你一些想法,如何使用 UI-Router 在这里.我相信,我正确理解您的挑战......有一个工作示例.如果这不是完全套房,请作为一些灵感

免责声明:使用 plunker,我无法做到这一点:http://m.amsterdamfoodie.nl/,但原理应该是example类似

所以,有一个状态定义(我们只有两个状态)

 $stateProvider.state('main', {网址:'/',意见:{'@':{templateUrl: 'tpl.layout.html',控制器:'MainCtrl',},'right@main' : { templateUrl: 'tpl.right.html',},'地图@主要':{templateUrl: 'tpl.map.html',控制器:'MapCtrl',},'列表@主':{templateUrl: 'tpl.list.html',控制器:'ListCtrl',},},}).state('main.criteria', {url: '^/criteria/:criteria/:value',意见:{'地图' : {templateUrl: 'tpl.map.html',控制器:'MapCtrl',},'列表' : {templateUrl: 'tpl.list.html',控制器:'ListCtrl',},},})}];

这将是我们的主要tpl.layout.html

<section class="map"><div ui-view="地图"></div></节><section class="list"><div ui-view="list"></div></节></节><section class="right"><div ui-view="right"></div></节>

正如我们所见,主状态确实针对主状态的这些嵌套视图:'viewName@main',例如'right@main'

也是子视图,main.criteria 确实注入了 layout 视图.

它的 url 以符号 ^ 开头(url : '^/criteria/:criteria/:value'),它允许有 //code> 主斜线,子斜线不是双斜线

还有控制器,它们在这里有点幼稚,但它们应该表明,后台可能是真实的数据加载(基于标准).

这里最重要的是,PARENT MainCtrl 创建了 $scope.Model = {}.此属性将(由于继承)在父母和孩子之间共享.这就是为什么这一切都会起作用的原因:

app.controller('MainCtrl', function($scope){$scope.Model = {};$scope.Model.data = ['Rest1', 'Rest2', 'Rest3', 'Rest4', 'Rest5'];$scope.Model.randOrd = function (){ return (Math.round(Math.random())-0.5);};}).controller('ListCtrl', function($scope, $stateParams){$scope.Model.list = []$scope.Model.data.sort( $scope.Model.randOrd ).forEach(function(i) {$scope.Model.list.push(i + " - " + $stateParams.value || "root")})$scope.Model.selected = $scope.Model.list[0];$scope.Model.select = 函数(索引){$scope.Model.selected = $scope.Model.list[index];}})

这应该对我们如何使用 UI-Router 为我们提供的功能有所了解:

工作示例

扩展:新 plunker 此处

如果我们不想重新创建地图视图,我们可以省略子状态 def 的形式:

.state('main.criteria', {url: '^/criteria/:criteria/:value',意见:{//'地图' : {//templateUrl: 'tpl.map.html',//控制器: 'MapCtrl',//},'列表' : {templateUrl: 'tpl.list.html',控制器:'ListCtrl',},},})

现在我们的地图 VIEW 将只接收模型中的更改(可以观看),但不会重新渲染视图和控制器

此外,还有另一个 plunker http://plnkr.co/edit/y0GzHv?p=使用 controllerAs

的预览

.state('main', {网址:'/',意见:{'@':{templateUrl: 'tpl.layout.html',控制器:'MainCtrl',controllerAs: 'main',//这里},...},}).state('main.criteria', {url: '^/criteria/:criteria/:value',意见:{'列表' : {templateUrl: 'tpl.list.html',控制器:'ListCtrl',controllerAs: 'list',//这里},},})

可以这样使用:

{{main.hello()}}

<h4>{{list.hello()}}</h4>

最后一个plunker是这里

I have an Angular SPA that presents a variety of recommendation lists, and a Google Map of locations, based on different cuts of some restaurant data (see m.amsterdamfoodie.nl). I want each of these lists to have their own URL. In order for Google to crawl the different lists I use <a> tags for the offcanvas navigation.

At present the <a> tag causes a view refresh, which is very noticeable with the map.

  • I can prevent this using ng-click and $event.preventDefault() (see code snippets below), but then I need to implement a means of updating the browser URL.
  • But in trying Angular's $state or the browser's history.pushstate, I end up triggering state changes and the view refresh...!

My question is therefore how can I update a model and the URL, but without refreshing the view? (See also Angular/UI-Router - How Can I Update The URL Without Refreshing Everything?)

I have experimented with a lot of approaches and currently have this html

<a href="criteria/price/1" class="btn btn-default" ng-click="main.action($event)">Budget</a>

In the controller:

this.action = ($event) ->
    $event.preventDefault()
    params = $event.target.href.match(/criteria\/(.*)\/(.*)$/)

    # seems to cause a view refresh
    # history.pushState({}, "page 2", "criteria/"+params[1]+"/"+params[2]);

    # seems to cause a view refresh
    # $state.transitionTo 'criteria', {criteria:params[1], q:params[2]}, {inherit:false}

    updateModel(...)

And, what is I think is happening is that I am triggering the $stateProvider code:

angular.module 'afmnewApp'
.config ($stateProvider) ->
  $stateProvider
  .state 'main',
    url: '/'
    templateUrl: 'app/main/main.html'
    controller: 'MainCtrl'
    controllerAs: 'main'
  .state 'criteria',
    url: '/criteria/:criteria/:q'
    templateUrl: 'app/main/main.html'
    controller: 'MainCtrl'
    controllerAs: 'main'

One possible clue is that with the code below if I load e.g. http://afmnew.herokuapp.com/criteria/cuisine/italian then the view refreshes as you navigate, whereas if I load http://afmnew.herokuapp.com/ there are no refreshes, but no URL updates instead. I don't understand why that is happening at all.

解决方案

Based on our previous discussions, I want to give you some idea, how to use UI-Router here. I believe, I understand your challenge properly... There is a working example. If this not fully suites, please take it as some inspiration

DISCLAIMER: With a plunker, I was not able to achieve this: http://m.amsterdamfoodie.nl/, but the principle should be in that example similar

So, there is a state definition (we have only two states)

  $stateProvider
    .state('main', {
        url: '/',
        views: {
          '@' : {
            templateUrl: 'tpl.layout.html',
            controller: 'MainCtrl',
          },
          'right@main' : { templateUrl: 'tpl.right.html',}, 
          'map@main' : {
            templateUrl: 'tpl.map.html',
            controller: 'MapCtrl',
          },
          'list@main' : {
            templateUrl: 'tpl.list.html',
            controller: 'ListCtrl',
          },
        },
      })
    .state('main.criteria', {
        url: '^/criteria/:criteria/:value',
        views: {
          'map' : {
            templateUrl: 'tpl.map.html',
            controller: 'MapCtrl',
          },
          'list' : {
            templateUrl: 'tpl.list.html',
            controller: 'ListCtrl',
          },
        },
      })
}];

This would be our main tpl.layout.html

<div>

  <section class="main">

    <section class="map">
      <div ui-view="map"></div>
    </section>

    <section class="list">
      <div ui-view="list"></div>
    </section>

  </section>

  <section class="right">
    <div ui-view="right"></div>
  </section>

</div>

As we can see, the main state does target these nested views of the main state: 'viewName@main', e.g. 'right@main'

Also the subview, main.criteria does inject into layout views.

Its url starts with a sign ^ (url : '^/criteria/:criteria/:value'), which allows to have / slash for main and not doubled slash for child

And also there are controllers, they are here a bit naive, but they should show, that on the background could be real data load (based on criteria).

The most important stuff here is, that the PARENT MainCtrl creates the $scope.Model = {}. This property will be (thanks to inheritance) shared among parent and children. That's why this all will work:

app.controller('MainCtrl', function($scope)
{
  $scope.Model = {};
  $scope.Model.data = ['Rest1', 'Rest2', 'Rest3', 'Rest4', 'Rest5'];  
  $scope.Model.randOrd = function (){ return (Math.round(Math.random())-0.5); };
})
.controller('ListCtrl', function($scope, $stateParams)
{
  $scope.Model.list = []
  $scope.Model.data
    .sort( $scope.Model.randOrd )
    .forEach(function(i) {$scope.Model.list.push(i + " - " + $stateParams.value || "root")})
  $scope.Model.selected = $scope.Model.list[0];
  $scope.Model.select = function(index){
    $scope.Model.selected = $scope.Model.list[index];  
  }
})

This should get some idea how we can use the features provided for us by UI-Router:

Check the above extract here, in the working example

Extend: new plunker here

If we do not want to have map view to be recreated, we can just omit that form the child state def:

.state('main.criteria', {
    url: '^/criteria/:criteria/:value',
    views: {
      // 'map' : {
      //  templateUrl: 'tpl.map.html',
      //  controller: 'MapCtrl',
      //},
      'list' : {
        templateUrl: 'tpl.list.html',
        controller: 'ListCtrl',
      },
    },
  })

Now our map VIEW will be just recieving changes in the model (could be watched) but view and controller won't be rerendered

ALSO, there is another plunker http://plnkr.co/edit/y0GzHv?p=preview which uses the controllerAs

.state('main', {
    url: '/',
    views: {
      '@' : {
        templateUrl: 'tpl.layout.html',
        controller: 'MainCtrl',
        controllerAs: 'main',        // here
      },
      ...
    },
  })
.state('main.criteria', {
    url: '^/criteria/:criteria/:value',
    views: {
      'list' : {
        templateUrl: 'tpl.list.html',
        controller: 'ListCtrl',
        controllerAs: 'list',      // here
      },
    },
  })

and that could be used like this:

<h4>{{main.hello()}}</h4>
<h4>{{list.hello()}}</h4>

The last plunker is here

这篇关于Angular-ui.router:在没有视图刷新的情况下更新 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆