用于AngularJS的UI路由器 - Hello World!

1.1 简介

  UI-Router是用于单页Web应用程序的客户端路由器。让我们为AngularJS Hello World应用程序构建一个UI路由器。它将有两个“页”(hello和about),每个都有自己的URL。我们可以通过点击链接在页面之间切换。活动页面的链接将被突出显示。

1.2 效果图


1.3 代码

详细解释及步骤见代码注释
1、index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>UI-Router01</title>

    <script src="lib/angular.js"></script>  //添加脚本标签
    <script src="lib/angular-ui-router.min.js"></script>
    <script src="js/helloworld.js"></script>

    <style>.active { color: red; font-weight: bold; }</style>
</head>
<body ng-app="helloworld">
    <a ui-sref="hello" ui-sref-active="active">Hello</a>
    //ui-sref是一个指令,行为类似于html的href。而不是引用的URL像href,它引用一个状态。该ui-sref指令根据您的状态的URL 自动href为您创建一个属性( a href=.../a )。
    <a ui-sref="about" ui-sref-active="active">About</a>
    //添加ui-sref-active="active"到ui-sref链接。active当目标状态为活动状态时,该指令将添加css类到链接。

    <ui-view></ui-view>     //该ui-view标签是一个UI-Router视口。当状态被激活时,状态的视图template:将被加载到视口中。
</body>
</html>

2、helloworld.js
// helloworld.js为应用程序代码创建一个新脚本并添加一个脚本标记。
var myApp = angular.module('helloworld', ['ui.router']);    //1.创建模块
// 我们告诉Angular ,helloworld是我们的主要模块,helloworld模块依赖于ui.router模块。

myApp.config(function($stateProvider) {
    var helloState = {  //2.创建状态
        name: 'hello',
        url: '/hello', //当状态为活动状态时,浏览器的网址将会是/hello。
        template: '<h3>hello world!</h3>'   //该template:字符串定义状态的视图。当状态为活动状态时,此视图将被加载到视口中。
    };

    var aboutState = {
        name: 'about',
        url: '/about',
        template: '<h3>Its the UI-Router hello world app!</h3>'
    };

    $stateProvider.state(helloState);   //因为$stateProvider是一个Angular提供者,您必须使用AngularJS依赖注入将其注入到.config()块中。
    $stateProvider.state(aboutState);
});

ps:

1、参考网站:https://ui-router.github.io/ng1/tutorial/helloworld

2、参考代码:QLY_AngularJS_UIRouter01

猜你喜欢

转载自blog.csdn.net/u013411654/article/details/77643277