search
HomeWeb Front-endJS TutorialNodejs uses Angular to create single-page applications

This time I will bring you Nodejs to use Angular to create a single-page application. What are the precautions for Nodejs to use Angular to create a single-page application. The following is a practical case, let's take a look.

Create a new app_client in the root directory to specifically place code related to a single page. Don’t forget to set it to static:

app.use(express.static(path.join(dirname, 'app_client')))
Angular routing

In a SPA application, switching between pages does not send a request to the background every time. This section moves the routing to the client, but retains the master page (layout.jade), and other views are implemented in Angular. To do this, first create a new angularApp method in the controller.

module.exports.angularApp = function (req, res) {
    res.render('layout', { title: 'ReadingClub' });
};
Set routing

router.get('/', ctrlOthers.angularApp);
The remaining Express routes are redundant, you can delete or comment them out. To avoid page reloading, Angular's default approach is to add a # sign to the url. The # sign is generally used as an anchor to locate points on the page, and Angular is used to access points in the application. For example, in Express, visit the about page:

/about
In Angular, the url will become

/#/about
. However, the # number can also be removed. After all, it does not look so intuitive. This is below. One section.

The old version of Angular library includes the routing module, but now it is used as an external dependency file and can be maintained by yourself. So you need to download and add it to the project first. https://code.angularjs.org/1.2.19/

Download angular-route.min.js and angular-route.min.js.map, and create an app.js under app_client

Add

    script(src='/angular/angular.min.js')
    script(src='/lib/angular-route.min.js')
    script(src='/app.js')
in layout.jade. You need to set module dependencies before using routing. It should be noted that the file name of the routing is angular-route, but the actual module The name is ngRoute. Under app_client/app.js:

angular.module('readApp', ['ngRoute']);
The ngRoute module will generate a $routeProvider object, which can be used to pass the configuration function, which is where we define the route:

function config($routeProvider) {
    $routeProvider
    .when('/', {})
    .otherwise({ redirectTo: '/' });
}
angular
.module('readApp')
.config(['$routeProvider', config]);
Review the previous $ When http, $scope, service and now $routeProvider appear in

function parameters , Angular will automatically obtain instances for us. This is Angular's dependency injection mechanism; the config method defines routing. At present, this route does not do much work, but the syntax is very intuitive. When the URL is '/', it does nothing when accessing the homepage. And when accessed by another URL, it jumps to the home page. Next we let this route do some work.

Angular View

First create a home folder under the app_client folder to place some files on the home page. But currently the home page is still a jade view, we need to convert it to html, so first create a home.view.html:

<p>
    </p><p>
        </p><p><a>全部</a><a>读书</a><a>书评</a><a>求书</a><a>求索</a></p>
        <p>
            <img  src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/061/021/e5289cf85d1925a677e4c8b5ebde7822-1.png?x-oss-process=image/resize,p_40" class="lazy" alt="Nodejs uses Angular to create single-page applications" ><span><i>{{topic.commentCount}}</i><i>/</i><i>{{topic.visitedCount}}</i></span>
            <span>{{topic.type}}</span><a>{{topic.title}}</a>
            <span>{{topic.createdOn}}</span><a>{{topic.author}}</a>
        </p>
    
    <p>
        </p><p>
            </p><p>{{user.userName}}</p>
        
    
Because there is no data yet, this html fragment will not do anything. The next step is to tell the Angular module to load this view when accessing the homepage. This is achieved through templateUrl, and the route is modified:

function config($routeProvider) {
    $routeProvider
    .when('/', {        templateUrl: 'home/home.view.html'
    })
    .otherwise({ redirectTo: '/' });
}
But this only provides a template address. Where does Angular start to replace it, like Asp. There is a

@RenderBody tag in Net MVC, which is block content in jade. This requires the use of a directive in the ngRoute module: ng-view. The marked element will be used by Angular as a container to switch views. We might as well add it above the block content:

    #bodycontent.container      p(ng-view)
        block content
Controller

With routing and views, we also need a controller. Also create a home.controller.js file in the home folder , first use

static data. After going through the previous section, this part is familiar.

angular
.module('readApp')
.controller('homeCtrl', homeCtrl);
function homeCtrl($scope) {
    $scope.data = topics;
    $scope.user = {
        userName: "stoneniqiu",
    };
}
Modify the route again:

function config($routeProvider) {
    $routeProvider
    .when('/', {
        templateUrl: 'home/home.view.html',        controller: 'homeCtrl',
    })
    .otherwise({ redirectTo: '/' });
}
At this time, visit the page and the data will come out. So whether it is Asp.net MVC, Express or Angular, the idea of ​​​​the MVC mode is the same. The request reaches the router first, and the router is responsible for forwarding it to the controller. The controller gets the data and then renders the view.

The difference from the previous section is that the ng-controller directive is not used on the page, but is specified in the routing.

 controllerAs 

 Angular提供了一个创建视图模型的方法来绑定数据,这样就不用每次直接修改$scope 对象,保持$scope 干净。 

function config($routeProvider) {
    $routeProvider
    .when('/', {
        templateUrl: 'home/home.view.html',
        controller: 'homeCtrl',        controllerAs: 'vm'
    })
    .otherwise({ redirectTo: '/' });
}

红色代码表示启用controllerAs语法,对应的视图模型名称是vm。这个时候Angular会将控制器中的this绑定到$scope上,而this又是一个上下文敏感的对象,所以先定义一个变量指向this。controller方法修改如下

function homeCtrl() {    var vm = this;
    vm.data = topics;
    vm.user = {
        userName: "stoneniqiu",
    };
}

注意我们已经拿掉了$scope参数。然后再修改下视图,加上前缀vm

<p>
    </p><p>
        </p><p><a>全部</a><a>读书</a><a>书评</a><a>求书</a><a>求索</a></p>
          <p>{{ vm.message }}</p>
          <p>
            <img  src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/061/021/e5289cf85d1925a677e4c8b5ebde7822-2.png?x-oss-process=image/resize,p_40" class="lazy" alt="Nodejs uses Angular to create single-page applications" ><span><i>{{topic.commentCount}}</i><i>/</i><i>{{topic.visitedCount}}</i></span>
            <span>{{topic.type}}</span><a>{{topic.title}}</a>
            <span>{{topic.createdOn}}</span><a>{{topic.author}}</a>
        </p>
    
    <p>
        </p><p>
            </p><p>{{vm.user.userName}}</p>
        
    

service:

 因为服务是给全局调用的,而不是只服务于home,所以再在app_clinet下新建一个目录:common/services文件夹,并创建一个ReadData.service.js :

angular
.module('readApp')
.service('topicData', topicData);function topicData ($http) {    return $http.get('/api/topics');
};

直接拿来上一节的代码。注意function写法, 最好用function fool()的方式,而不要var fool=function() 前者和后者的区别是前者的声明会置顶。而后者必须写在调用语句的前面,不然就是undefined。修改layout

    script(src='/app.js')
    script(src='/home/home.controller.js')
    script(src='/common/services/ReadData.service.js')

相应的home.controller.js 改动:

function homeCtrl(topicData) {    var vm = this;
    vm.message = "loading...";
    topicData.success(function (data) {
        console.log(data);
        vm.message = data.length > 0 ? "" : "暂无数据";
        vm.data = data;
    }).error(function (e) {
        console.log(e);
        vm.message = "Sorry, something's gone wrong ";
    });
    vm.user = {
        userName: "stoneniqiu",
    };
}

这个时候页面已经出来了,但是日期格式不友好。接下来添加过滤器和指令

filter&directive

 在common文件夹创建一个filters目录,并创建一个formatDate.filter.js文件,同上一节一样

angular
.module('readApp')
.filter('formatDate', formatDate);function formatDate() {    return function (dateStr) {        var date = new Date(dateStr);        var d = date.getDate();        var monthNames = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"];        var m = monthNames[date.getMonth()];        var y = date.getFullYear();        var output = y + '/' + m + '/' + d;        return output;
    };
};

然后在common文件夹下新建一个directive文件夹,再在directive目录下新建一个ratingStars目录。ratingStars指令会在多个地方使用,它包含一个js文件和一个html文件,将上一节的模板文件复制过来,并命名为:ratingStars.template.html。然后新建一个ratingStars.directive.js文件,拷贝之前的指令代码,并改造两处。

angular
.module('readApp')
.directive('ratingStars', ratingStars);function ratingStars () {return {
restrict: 'EA',scope: {
thisRating : '=rating'},templateUrl: '/common/directive/ratingStars/ratingStars.template.html'};
}

EA表示指令作用的范围,E表示元素(element),A表示属性(attribute),A是默认值。还C表示样式名(class),M表示注释(comment), 最佳实践还是EA。更多知识可以参考这篇博客 Angular指令详解

因为还没有创建booksController,先用topic.commentCount来测试ratingStars指令,并记得在layout下添加引用

  <p>
            <img  src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/061/021/e5289cf85d1925a677e4c8b5ebde7822-2.png?x-oss-process=image/resize,p_40" class="lazy" alt="Nodejs uses Angular to create single-page applications" ><span><i>{{topic.commentCount}}</i><i>/</i><i>{{topic.visitedCount}}</i></span>
               <small></small>
               <span>{{topic.type}}</span><a>{{topic.title}}</a>
            <span>{{topic.createdOn | formatDate}}</span><a>{{topic.author}}</a>
        </p>

 这个时候效果已经出来了。

有哪些优化?

这一节和上一节相比,展现的内容基本没有变化,但组织代码的结构变得更清晰好维护了,但还是不够好,比如layout里面我们增加了过多的js引用。这也是很烦的事情。所以我们可以做一些优化:

1.减少全局变量  

第一点,在团队开发的时候要尽量减少全局变量,不然容易混淆和替换,最简单的办法就是用匿名函数包裹起来:

(function() { //....})();

被包裹的内容会在全局作用域下隐藏起来。而且在这个Angular应用也不需要通过全局作用域关联,因为模块之间都是通过angular.module('readApp', ['ngRoute'])连接的。controller、service、directive这些js都可以处理一下。

2.减少JavaScript的尺寸

我们可以让js最小化,但有一个问题,在controller中的依赖注入会受影响。因为JavaScript在最小化的时候,会将一些变量替换成a,b,c

function homeCtrl ($scope, topicData, otherData)

会变成:

function homeCtrl(a,b,c){

这样依赖注入就会失效。这个时候怎么办呢,就要用到$inject ,$inject作用在方法名称后面,等于是声明当前方法有哪些依赖项。

homeCtrl.$inject = ['$scope', 'topicData', 'otherData'];function homeCtrl ($scope, topicData, otherData) {

$inject数组中的名字是不会在最小化的时候被替换掉的。但记住顺序要和方法的调用顺序一致。

topicData.$inject = ['$http'];function topicData ($http) {    return $http.get('/api/topics');
};

做好了这个准备,接下来就可以最小化了

3.减少文件下载

在layout中我们引用了好几个js,这样很烦,可以使用UglifyJS 去最小化JavaScript文件。 UglifyJS 能将Angular应用的源文件合并成一个文件然后压缩,而我们只需在layout中引用它的输出文件即可。 

 安装:

 

 然后在根目录/app.js中引用

var uglifyJs = require("uglifyjs");var fs = require('fs');

接下来有三步

1.列出需要合并的文件

2.调用uglifyJs 来合并并压缩文件。

3.然后保存在Public目录下。

在/app.js下var一个appClientFiles数组,包含要压缩的对象。然后调用uglifyjs.minify方法压缩,然后写入public/angular/readApp.min.js

var appClientFiles = [    'app_client/app.js',    'app_client/home/home.controller.js',    'app_client/common/services/ReadData.service.js',    'app_client/common/filters/formatDate.filter.js',    'app_client/common/directive/ratingStars/ratingStars.directive.js'];var uglified = uglifyJs.minify(appClientFiles, { compress : false });
fs.writeFile('public/angular/readApp.min.js', uglified.code, function (err) {    if (err) {
        console.log(err);
    } else {
        console.log('脚本生产并保存成功: readApp.min.js');
    }
});

最后修改layout:

    script(src='/angular/readApp.min.js')    //script(src='/app.js')
    //script(src='/home/home.controller.js')
    //script(src='/common/services/ReadData.service.js')
    //script(src='/common/filters/formatDate.filter.js')
    //script(src='/common/directive/ratingStars/ratingStars.directive.js')

这里选择注释而不是删掉,为了便于后面的调试。但如果用nodemon启动,它会一直在重启。因为生产文件的时候触发了nodemon重启,如此循环。所以这里需要一个配置文件告诉nodemon忽略掉这个文件的改变。在根目录下新增一个文件nodemon.json

{  "verbose": true,  "ignore": ["public//angular/readApp.min.js"]
}

这样就得到了一个min.js 。原本5个文件是5kb,换成min之后是2kb。所以这个优化还是很明显的。

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

推荐阅读:

Nodejs的form验证及图片上传 

JavaScript的事件管理

The above is the detailed content of Nodejs uses Angular to create single-page applications. 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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools