Home  >  Article  >  Web Front-end  >  Introduction to using Angular with Node.js

Introduction to using Angular with Node.js

不言
不言Original
2018-06-30 14:28:081343browse

This article mainly introduces a simple example of using Angular in Node.js, and how to introduce AngularJS into a Node.js project. This time, a very simple example is provided to demonstrate the instructions, data binding, services, etc. in AngularJS. Interested friends can refer to

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

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(&#39;x-admin&#39;, []).
controller(&#39;x-controller&#39;, function ($scope, $http) {
 $scope.currentUser="ZhangSan";
 $scope.content = &#39;/welcome.html&#39;;

 $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(&#39;x-admin&#39;, [])

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.

When using angular.module to define a module, the second parameter is a list of dependent modules, and Angular will automatically solve the dependency injection problem for you. For example, if you rely on ui bootstrap, you can write like this:

angular.module(&#39;x-admin&#39;, [&#39;ui.bootstrap&#39;])

It should be noted that when describing instructions in the document, they are always in the form of ngApp, and when writing code, it is in the form of ng-app. Angular’s ​​documentation is pretty good, I like it.

5. Add a controller

There is this line of code in the admin.html document:

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

The above code changes the name to "x-controller " controller is assigned to the

element, so that we can use the data (Model) in the scope of the controller with the same name defined in js in this element.

The second line of code in admin.js:

controller(&#39;x-controller&#39;, function ($scope, $http) {

defines a controller. For specific syntax, please refer here: http://docs.angularjs.cn/api. Domestic, no need to turn over the gun.

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

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

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

controller(&#39;x-controller&#39;,[&#39;$scope&#39;, &#39;$http&#39;, 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已经说过了。咱说没提过的。

<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>

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

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

angular.module(&#39;x-admin&#39;, []).
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指令可以指定某个元素被点击时的响应(函数)。

<input type="button" class="sidemenu-button" value="{{subMenu.text}}" ng-click="setContent(subMenu.action)">

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

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

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

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

上面的代码使用ng-include指令来包含一个HTML片段。当你使用ng-include指定了一个html片段后,Angular会解析这个指令,获取对应的html文档,编译,并且将其内容整合进原始html文档内。

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

Node中cluster模块的学习

nodejs实现bigpipe异步加载页面的方法

The above is the detailed content of Introduction to using Angular with Node.js. 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