项目上有一个新需求,就是需要根据json文件动态生成路由状态,查阅了一下资料,现在总结一下发出来:

首先项目用到的是angular的UI-路由,所以必须引入angular.js和angular-ui-router.js两个js文件,如下例子:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Example</title>
  <script src="/UploadFiles/2021-04-02/angular.js">

然后是json文件的一些数据,如下

{  "xxx": {
    "url": "/xxx",
    "templateUrl": "templates/xxx.html"
  },
  "yyy": {
    "url": "/yyy",
    "templateUrl": "templates/yyy.html"
  },
  "ccc": {
    "url": "/ccc",
    "templateUrl": "templates/yyy.html"
  },
  "zzz": {
    "url": "/zzz",
    "templateUrl": "templates/zzz.html"
  }
}

之后定义一个服务,定义个方法用来配置获取json文件的ajax请求的地址,主方法是发送ajax并且对结果进行循环写入路由状态。

'use strict'
angular.module('Routing', ['ui.router'])
  .provider('router', function ($stateProvider) {
    var urlCollection;
    this.$get = function ($http, $state) {
      return {
        setUpRoutes: function () {
          $http.get(urlCollection).success(function (collection) {
            for (var routeName in collection) {
              if (!$state.get(routeName)) {
                $stateProvider.state(routeName, collection[routeName]);
              }
            }
          });
        }
      }
    };
    this.setCollectionUrl = function (url) {
      urlCollection = url;
    }
  })

最后是最关键的angular配置阶段和运行阶段的代码,配置阶段要求至少给出一种状态,如$stateProvider.state('home', {url: '/home',templateUrl: 'templates/home.html'});

并且将默认状态配置好$urlRouterProvider.otherwise('/home');随后调用上面的服务的setCollectionUrl 方法对url地址进行配置,方便发送ajax请求,最后在angular的运行阶段的run方法中调用setUpRoutes方法将json文件的数据根据一定的格式进行状态的动态写入,代码如下:

angular.module('App', ['ui.router', 'Routing'])
  .config(function ($stateProvider, $urlRouterProvider, routerProvider) {
    $stateProvider
      .state('home', {
        url: '/home',
        templateUrl: 'templates/home.html'
      });
    $urlRouterProvider.otherwise('/home');
    routerProvider.setCollectionUrl('js/routeCollection.json');
  })
  .run(function (router) {
    router.setUpRoutes();
  })
;

此,动态获取angular路由状态的例子就介绍完了,感兴趣的可以看下原文地址和原文代码的github,分别如下:

github地址

 github上用git clone下来之后,会看到项目中有个bower.json文件,并且没有上述的两个js文件,我们只需在工程中使用node的包管理器npm下载bower,然后在该项目的命令行中输入bower install 即可下载下来项目要用到的js文件。

以上所述是小编给大家介绍的Angularjs根据json文件动态生成路由状态,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

标签:
angular,json,angular,路由状态

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com

RTX 5090要首发 性能要翻倍!三星展示GDDR7显存

三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。

首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。

据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。