javascript Angularjs 在没有 ng-view 的情况下使用 $routeProvider

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15335338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:25:30  来源:igfitidea点击:

Angularjs using $routeProvider without ng-view

javascriptangularjs

提问by mattl

I have a simple single page app that shows images on it.

我有一个简单的单页应用程序,可以在上面显示图像。

On first load the page is blank and people add their own images however if they then return to the page with their saved id in the url then I want the page to grab the previous model.

在第一次加载时,页面是空白的,人们添加自己的图像,但是如果他们然后返回到带有保存在 url 中的 id 的页面,那么我希望页面抓取以前的模型。

Now all my previous attempts to use routeProvider have failed unless I put ng-view somewhere in the page. But this then affects the scopes that are inside the ng-view scope.

现在,除非我将 ng-view 放在页面中的某个位置,否则我之前使用 routeProvider 的所有尝试都失败了。但这会影响 ng-view 范围内的范围。

Basically I need to respond differently on the page depending if there is an id in the url or not but I'm not changing the view and I need to get the id from the route parameters.

基本上,我需要在页面上做出不同的响应,具体取决于 url 中是否有 id,但我没有更改视图,我需要从路由参数中获取 id。

So I was just wondering how you guys would go about doing this as I seem to be barking up the wrong trees! Any help would be much appreciated.

所以我只是想知道你们会怎么做,因为我似乎在吠错树!任何帮助将非常感激。

回答by Stewie

Here's one way to handle url with and without id, using standard routeProvider setup, with one controller:

这是使用标准 routeProvider 设置和一个控制器处理带和不带 id url 的一种方法:

JS:

JS:

var app = angular.module('plunker', []);

app.config(function($routeProvider){
  return $routeProvider
    .when('/', {
      controller: 'HomeController',
      templateUrl: 'home.html'
    })
    .when('/:id', {
      controller: 'HomeController',
      templateUrl: 'home.html'
    })
    .otherwise({ redirectTo: '/' });
});

app.controller('HomeController',
    [
      '$scope',
      '$routeParams',
      function($scope, $routeParams) {
        if($routeParams.id){
          $scope.id = $routeParams.id;
          // handle scenario when there is an id in URL
          return;
        }

        // handle scenario when there is no id
        $scope.id = 'no ID!!';
      }
    ]
  );

Plunker

Plunker

And here's another way, without using ng-view and relying on $location service:

这是另一种方式,不使用 ng-view 并依赖 $location 服务:

var app = angular.module('plunker', []);

app.config(
    ['$locationProvider',
      function($locationProvider) {
        $locationProvider.html5Mode(true);
      }
    ]
  );

app.controller('HomeController',
    [
      '$scope',
      '$location',
      function($scope, $location) {

        $scope.$watch(function(){
            return $location.hash();
          },
          function(id){
            $scope.id = id;
          }
        );

        $scope.$watch('id', function(id){
          if(id){
            // handle scenario when there's id available
            return;
          }
          // handle scenario when there is no id
        });

      }
    ]
  );

Plunker

Plunker

回答by Mike Fabrikant

This plunkerinitiates a $route service by adding $routeas a dependency in the app run block. The idea is described here.

这个 plunker通过$route在应用程序运行块中添加一个依赖项来启动一个 $route 服务。这里描述这个想法。

angular.module('myApp', ['myApp.controllers'])
  .config(function($routeProvider) {
    return $routeProvider.when("/", {
      controller: 'firstCtrl'
    }).when("/numbers/:number", {
      controller: 'secondCtrl'
    });
  }).run(function($route) {});

angular.module("myApp.controllers", [])
  .controller("firstCtrl", function($scope) {
    $scope.numbers = [1, 2, 3];
  })
  .controller("secondCtrl", function($scope,$routeParams, $rootScope, $location) {
    return $rootScope.$on("$routeChangeSuccess", function(event, current) {
      $scope.current_path = $location.$$path;
      $scope.number = $routeParams['number'];
    });
  });

回答by Jeremy Reed

You could do something similar to what Ben Nadel suggests. That is using ng-switch and have a hash value for a key in deciding what template to render coupled with ng-include. That way when you change to a different url path, you listen for that change, update the the model, and fire off a new include/partial.

你可以做一些类似于 Ben Nadel 建议的事情。那就是使用 ng-switch 并有一个键的哈希值来决定要呈现的模板与 ng-include 结合。这样,当您更改为不同的 url 路径时,您会监听该更改、更新模型并触发新的包含/部分。

Ben Nadel - Nested Views, Routing, And Deep Linking With AngularJS

Ben Nadel - 嵌套视图、路由和与 AngularJS 的深度链接

回答by Jo?o Rodrigues

You can always define your own url parser. Create a service and then use when and where you want.

您始终可以定义自己的 url 解析器。创建一个服务,然后在您想要的时间和地点使用。

angular.module('app').service('urlParser', function(){
    this.parse = function(url){
        var query = url.split('?')
        if (url.length == 1){ return {} } //it means it has no parameters
        else{
            var paramsArray = query.split('&')
            var params = {} //this is going to be your return object
            var i;
            for ( i=0; i < paramsArray.length; i++ ){
                var arr = paramsArray[i].split('=')
                var param = arr[0]
                var value;
                //check if is set with some value
                if( arr.length == 1 )
                    value = null
                else
                    value = arr[1]
                obj[param] = value
            }
            return obj;
        }
    }
})

And you will be calling it from you controller as a service. Name of service: urlParser Name of method: parse(:string)

你将从你的控制器调用它作为服务。服务名称:urlParser 方法名称:parse(:string)

Example:
var url = "http://www.yourwebsite.com/yourroute?page=1&user=1000"
var params = urlParser.parse(url)
params.page //gives you 1
params.user //gives you 1000

Hope this helped

示例:
var url = " http://www.yourwebsite.com/yourroute?page=1&user=1000"
var params = urlParser.parse(url)
params.page //gives you 1
params.user //gives you 1000

Hope这有帮助