Home  >  Article  >  Web Front-end  >  Node.js uses Angular for practical analysis

Node.js uses Angular for practical analysis

php中世界最好的语言
php中世界最好的语言Original
2018-05-30 11:29:11913browse

This time I will bring you a practical analysis of using Angular in Node.js. What are the precautions for using Angular in Node.js? The following is a practical case, let's take a look.

In "Using AngularJS", we mentioned how to introduce AngularJS into a Node.js project. This time we provide a very simple example to demonstrate the instructions and data binding in AngularJS. , services and other contents.

I plan to build a Web backend management system. Different administrators will have different permissions. The menu the administrator sees after logging in is related to his permissions. What he can see is dynamically generated (similar to RBAC ). The examples in this article come from this project, and of course, are still the simplest.

If there is no special instructions, the examples we use later will be generated using express generator.

Angular small demo

Let’s start with it.

The first step is to enter the myprojects directory and execute "express AngularDemo".

The second step, navigate to the AngularDemo directory, execute "npm install"

The third step, go to AngularJS to download the latest AngularJS library file, I downloaded the 1.4.3 min version, re- Name it "angular-1.4.3.min.js" and place it under AngularDemo/public/javascripts. For our simple Demo, only this one file is enough.

The fourth step is to prepare the files we want to use.

The first is admin.html, which can be placed under AngularDemo/public. The encoding format of admin.html should use UTF8. The content is as follows:

<!DOCTYPE html>
<html ng-app="x-admin">
 <head>
  <meta charset="UTF-8">
  <title>X管理系统</title>
  <link rel="stylesheet" href="/stylesheets/admin.css" rel="external nofollow" >
 </head>
 <body>
  <p class="x-view-full" ng-controller="x-controller">
    <p class="x-project-header">
     <p id="x-project-title">X管理后台</p>
     <p id="x-login-user"><a href="/user/tttt" rel="external nofollow" rel="external nofollow" >{{currentUser}}</a> <a href="/logout" rel="external nofollow" rel="external nofollow" >退出</a></p>
    </p>
    <p class="x-sidemenu">
     <p class="x-sidemenu-one" ng-repeat="menu in menus" ng-show="menu.enabled">
      <p class="sidemenu-one">{{menu.text}}</p>
      <p class="x-sidemenu-two" ng-repeat="subMenu in menu.subMenus" ng-show="subMenu.enabled">
       <input type="button" class="sidemenu-button" value="{{subMenu.text}}" ng-click="setContent(subMenu.action)"></input>
      </p>
     </p>
    </p>
    <p class="x-contents">
     <p ng-include="content"></p>
    </p>
  </p>
  <script src="/javascripts/angular-1.4.3.min.js"></script>
  <script src="/javascripts/admin.js"></script>
 </body>
</html>

Then comes the admin.js file, placed under AngularDemo/public/javascripts. UTF8 encoding, the content is as follows:

angular.module('x-admin', []).
controller('x-controller', function ($scope, $http) {
 $scope.currentUser="ZhangSan";
 $scope.content = '/welcome.html';
 $scope.menus = [
  {
   text: "系统管理",
   enabled: true,
   subMenus:[
    {
     text: "用户管理",
     enabled: true,
     action:"/login.html"
    },
    {
     text: "角色管理",
     enabled: true,
     action:"/role"    
    },
    {
     text: "权限管理",
     enabled: true,
     action:"/access"    
    }
   ]
  },
  {
   text: "内容管理",
   enabled: true,
   subMenus:[
    {
     text: "直播监控",
     enabled: true,
     action:"/stream-monitor"
    },
    {
     text: "预约管理",
     enabled: true,
     action:"/book-mgr"    
    }
   ]  
  },
  {
   text: "推送管理",
   enabled: true,
   subMenus:[
    {
     text: "推送列表",
     enabled: true,
     action:"/push-list"
    },
    {
     text: "新增推送",
     enabled: true,
     action:"/add-push"    
    }
   ]  
  }  
 ]; 
 $scope.setContent = function(action){
  console.log(action);
  $scope.content=action;
 };
});

Next, I wrote a simple CSS file-admin.css, and placed it under AngularDemo/public/stylesheets. The content is as follows:

a {
 color: #00B7FF;
}
p.x-view-full {
 width: 100%;
 height: 100%;
}
p.x-project-header {
 display: inline-block;
 position: absolute;
 border: 1px solid #E4E4E4;
 background: #F2F2F2;
 width: 100%;
 height: 60px;
 left: 0px;
 top: 0px;
}
p.x-sidemenu {
 display: inline-block;
 position: absolute;
 border: 1px solid #E4E4E4;
 background: #F2F2F2;
 left: 0px;
 top: 66px;
 width: 160px;
 height: 600px; 
}
p.x-contents {
 display: inline-block;
 position: absolute;
 left: 170px;
 top: 66px;
 min-width: 200px;
 min-height: 200px;
}
p.x-sidemenu-one{
 margin-left: 8px;
}
p.x-sidemenu-two{
 margin-left: 14px;
 font-size: 14px;
}
p.sidemenu-one{
 font-size: 18px;
 font-weight: bold;
 color: black;
}
.sidemenu-button{
 font-size: 14px;
 border: 0px;
 margin-bottom: 6px;
 background: #F2F2F2;
}
.sidemenu-button:hover {background-color: #218fd5;}
#x-project-title{
 position: absolute;
 display: inline-block;
 top: 20px;
 left: 20px;
 font-size: 28px;
 font-weight: bold;
 width: 200px;
}
#x-login-user{
 position: absolute;
 display: inline-block;
 top: 30px;
 right: 10px;
 width: 200px; 
 text-align: right;
}
p.admin-addUser{
 position: relative;
 top: 4px;
 left: 10px;
 width: auto;
 height: auto;
}

Finally, in order to demonstrate the menu function, we also need two static html files, welcome.html and login.html, both of which can be placed under public.

welcome.html content is as follows:

Welcome to X-Manager!

login.html content is as follows (note, UTF8 encoding):

<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <title>登录</title>
 </head>
 <body>
  <p class="form-container">
    <p class="form-header">登录</p>
    <form action=&#39;login&#39; method=&#39;POST&#39; align="center">
     <table>
      <tr>
        <td><label for="user">账号:</label></td>
        <td><input type="text" id="user" name="login_username" /></td>
      </tr>
      <tr>
        <td><label for="pwd">密码:</label></td>
        <td><input type="password" id="pwd" name="login_password" /></td>
      </tr>
      <tr>
       <td colspan=&#39;2&#39; align="right">
        <a href="/signup" rel="external nofollow" >注册</a>
        <input type="submit" value=&#39;登录&#39;/>
       </td>
      </tr>
     </table>
    </form>
  </p>
 </body>
</html>

The fifth step, in the AngularDemo directory, execute "npm start" command to start the website.

The sixth step is to visit "http://localhost:3000/admin.html" in the browser. You should see the following effect:

Steps to create a basic AngularJS application

What we did earlier No matter what, let’s run AngularDemo first. Now let's look at the steps to create a basic AngularJS application.

The first step is to implement a Node.js web server. This express does it for us. We use the default application template. If you look at app.js, you should find that it uses the app.static middleware to process the public directory. We can directly access the public directory in the browser. file, such as http://localhost:3000/admin.html.

The second step is to implement an AngularJS HTML template, such as our admin.html. This is the most important, let’s take a look.

1. Load the AngularJS library

Well, the script element is placed at the end of the body element of the HTML document, like admin.html. The browser will download and execute the angular-1.4.3.min.js file for you. The HTML code is as follows:

<script src="/javascripts/angular-1.4.3.min.js"></script>

2. Implement your Angular module

For example, admin.js in our example, which implements a controller to support HTML templates.

3. Load your main module

script element and place it after the angular library. This is necessary. The HTML code is as follows:

<script src="/javascripts/admin.js"></script>

4. Define the root element

admin.html has this line of code:

<html ng-app="x-admin">

The first line of code in admin.js

angular.module('x-admin', [])

These two lines of code are corresponding. The Angular module name is specified using the ng-app directive in HTML. This module name is the first parameter provided when you use angular.module to define the module in your js code. For our example, the module name is "x-admin".

After ng-app is associated in HTML, you can add the controller.

For the ng-app directive and angular.module method, please refer here: http://docs.angularjs.cn/api. Domestic, no need to turn over the gun.

使用angular.module定义模块时,第二个参数是依赖的模块列表,Angular会自动为你解决依赖注入问题。比如你依赖ui bootstrap,可以这么写:

angular.module('x-admin', ['ui.bootstrap'])

需要注意的是:文档里描述指令时,都是ngApp这种形式,而写代码时,是ng-app。angular的文档还是不错的,赞一个。

5. 添加控制器

admin.html文档中有这行代码:

<p class="x-view-full" ng-controller="x-controller">

上面的代码把名字是“x-controller”的控制器分配到

元素中,这样我们就可以在这个元素中使用js里定义的同名控制器的作用域内的数据(Model)。

admin.js的第2行代码:

controller('x-controller', function ($scope, $http) {

定义了一个控制器。具体的语法参考这里吧:http://docs.angularjs.cn/api。国内的,无需翻qiang。

controller是angular.Module的一个方法,用来定义控制器,原型是: controller(name, constructor);

第一个参数是控制器的名字,第二个参数是控制器的构造函数。构造函数的参数是控制器依赖的服务。

还有一种语法controller(name,[]),第二个参数是控制器的依赖数组。比如:

复制代码 代码如下:

controller('x-controller',['$scope', '$http', function($scope, $http){}]);

我看1.3.x,1.4.x的文档里controller方法的原型都是第一种,第二种是我在《Node.js+MongoDB+AngularJS Web开发》里看到。两种我都测试了,都可以用。但跟什么版本什么关系,存疑了。

6. 实现作用域模型

使用Module的controller方法定义控制器时,会让开发者提供控制器的构造函数。当Angular编译HTML时,会使用开发者提供的控制器构造函数创建控制器的实例。构造函数内,会初始化一些数据,关联到作用域scope里的数据和方法,都可以直接被HTML引用。

我在admin.js里x-controller控制器的构造函数内,提供了menus数组,用于构造管理界面的左侧菜单;提供了currentUser,显示在管理界面右上角;content则用来保存管理界面左下角区域使用的局部html模板;最后呢,提供了一个setContent方法,以便用户可以通过管理界面的菜单来更改content,进而改变功能区域的内容。

7. 在HTML模板中使用指令和绑定数据

其实在实现作用域模型时,心里对“什么数据和哪个HTML元素对应”这一点是一清二楚的,不清楚你也实现不来啊不是。

一旦你实现了作用域模型,就可以在HTML模板里使用ng指令来关联数据了。其实有时候你是先写HTML模板,还是先实现作用域模型,还真分不太清楚。

我们以admin.html为例来说明一下ng指令的用法,注意,只提admin.html中用到的,没用到就看http://docs.angularjs.cn/api。我们用到了ng-app、ng-controller、ng-repeat、ng-click、ng-show、ng-include、{{}}。

ng-app和ng-controller已经说过了。咱说没提过的。

复制代码 代码如下:

{{currentUser}} 退出

这行代码里用到了{{expression}}这种语法,花括号之间是一个使用作用域内的变量构成的JS表达式。示例里直接引用了currentUser变量,实际运行中会用admin.js里的currentUser的值替换HTML文档中的这部分代码。如果在运行过程中currentUser变量的值发生变化,HTML也会变化,这是数据绑定。

我们可以修改一下admin.js,使用$interval服务来启动一个定时器,修改currentUser的值。新的admin.js是这样的:

angular.module('x-admin', []).
controller('x-controller', function ($scope, $http, $interval) {
 $scope.currentUser="ZhangSan";
 $scope.content = '/welcome.html';
 $scope.menus = [
  ...... 
 ]; 
 $scope.setContent = function(action){
  console.log(action);
  $scope.content=action;
 };
 //2秒后改变一次currentUser
 $interval(function(){
  $scope.currentUser = "LiSi";
 }, 2000, 1);
});

ng-repeat指令可以根据一个集合,使用一个模板化的item来创建多个相似的HTML元素。

<p class="x-sidemenu-one" ng-repeat="menu in menus" ng-show="menu.enabled">

上面的代码使用ng-repeat指令,根据x-controller里定义的menus数组来创建多个

元素,每个都具有相同的结构。在ng-repeat指令内,通常使用“x in collections”这种语法来遍历作用域中的某个集合,而x又可以在ng-repeat定义的模板元素内部使用。比如上面定义的p模板,使用ng-show指令时就使用了“menu in menus”中定义的menu变量。同时这个p模板内部代码也引用了menu,参看下面的代码:

<p class="sidemenu-one">{{menu.text}}</p>

ng-show指令放在某个HTML元素内部,用来指示是否显示该元素。

ng-click指令可以指定某个元素被点击时的响应(函数)。

复制代码 代码如下:

上面的代码使用ng-click指令为代表子菜单的按钮指定了响应鼠标点击的代码“setContent(subMenu.action)”。setContent是作用域内定义的方法,subMenu是ng-repeat指令内定义的变量。

有了这样的处理,当用户点击某个菜单时,就会调用到admin.js里的setContent方法来改变content的值。而这种改变,会反过来影响HTML的效果,改变管理页面左下区域内显示的内容。示例里当你点击用户管理时会显示一个登陆页面。

促成这种效果的代码如下:

<p ng-include="content"></p>

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

怎样操作Node.js 使用jade模板引擎

怎样使用node前端开发模板引擎Jade

The above is the detailed content of Node.js uses Angular for practical analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn