search
HomeWeb Front-endJS TutorialHow to use Node.js dialog box ngDialog

How to use Node.js dialog box ngDialog

May 30, 2018 am 11:37 AM
javascriptnode.jsdialog box

This time I will show you how to use the dialog box ngDialog in Node.js, and what are the precautions when operating Node.js and use the dialog box ngDialog. The following is a practical case, let's take a look.

When building a website, we often encounter situations where a dialog box pops up to obtain user input or a dialog box pops up to ask the user to confirm an operation. There is an extension module based on AngularJS that can help us accomplish this kind of thing elegantly: ngDialog.

ngDialog provides an example web page on github demonstrating its various uses, here: https://github.com/likeastore/ngDialog/blob/master/example /index.html. The readme of ngDialog's github homepage also provides a more detailed introduction to commonly used instructions and services, which you can refer to. My article is purely based on the ngDialog example.

Create a dialog box using ngDialog.open(options) or ngDialog.openConfirm(options). The former opens a normal dialog box, and a series of attributes such as themes and templates can be specified through options. The latter opens a dialog box that by default refuses escape to close and automatically closes outside of the dialog box. options is a json object, similar to the following:

{template: 'tplId',closeByEscape: false}

Example setup

Let’s take a look at my simple example first. Use the express generator to create a new application, or directly use the LoginDemo example in Getting Started with Node.js Development - Using Cookies to Stay Logged In. Everything is done.

Add files written by yourself

There are three files written by yourself. The ngdialog.html and serverTpl.html files are placed in the public directory of the project, and ngdialog.js is placed in the public directory of the project. Under public/javascripts.

ngdialog.html content:

nbsp;html>


 <title>use ngDialog in AngularJS</title>
 <link><link>
 <link><link>
 <link><link>


 <p><button>Open Default</button></p>
 <p><button>Open Plain theme</button></p>
 <p><button>Open use text</button></p>
 <p><button>Open modal</button></p>
 <p><button>Open use template on server</button></p>
 <p><button>Open Confirm</button></p>
 <script></script>
 <script></script>
 <script></script>
 <!-- Templates -->
 <script>
  <p><p>text in dialog
 </script>

ngdialog.js content:

angular.module('myApp', ['ngDialog']).
 controller('myController', function($scope,$rootScope, ngDialog){
  $scope.template = '<p></p><p>text in dialog</p><p><button>Button</button></p><p>';
  //different template
  $scope.openDialog = function(){
   ngDialog.open({template: 'firstDialogId'});
  };
  $scope.openPlainDialog = function(){
   ngDialog.open({
    template: 'firstDialogId', //use template id defined in HTML
    className: 'ngdialog-theme-plain'
   });
  }
  $scope.openDialogUseText = function(){
   ngDialog.open({
    template: $scope.template, //use plain text as template
    plain: true,
    className: 'ngdialog-theme-plain'
   });
  }
  $scope.openModal = function(){
   ngDialog.open({
    template: '</p><p>Text in Modal Dialog</p>',
    plain: true,
    className: 'ngdialog-theme-default',
    closeByEscape: false,
    closeByDocument: false
   });
  }
  $scope.openUseExternalTemplate = function(){
   ngDialog.open({
    template: 'serverTpl.html',
    plain: false,
    className: 'ngdialog-theme-default',
    closeByEscape: false,
    closeByDocument: false
   });
  };
  $rootScope.userName = "ZhangSan";
  $scope.openConfirmDialog = function(){
   ngDialog.openConfirm({
    template: '<p></p><h3 id="Please-enter-your-name">Please enter your name</h3><p>User Name:<input></p><p><button>Cancel</button><button>Confirm</button></p>',
    plain: true,
    className: 'ngdialog-theme-default'
   }).then(
    function(value){
     console.log('confirmed, value - ', value);
    },
    function(reason){
     console.log('rejected, reason - ', reason);
    }
   );
  }
  //listen events
  $rootScope.$on('ngDialog.opened', function (e, $dialog) {
    console.log('ngDialog opened: ' + $dialog.attr('id'));
  });
  $rootScope.$on('ngDialog.closed', function (e, $dialog) {
    console.log('ngDialog closed: ' + $dialog.attr('id'));
  });  
 });

serverTpl.html content:

nbsp;html>


 <title>A Server Template for ngDialog</title>


 <p>
  </p><h3 id="Server-Template-for-ngDialog">Server Template for ngDialog</h3>
  
  • Node.js
  •   
  • Express
  •   
  • AngularJS
  •   
  • MongoDB
  •  

    Introducing ngDialog

    To use ngDialog, you need to use script to introduce the corresponding js library file in HTML. In addition, several css files must be introduced in the head part. Just refer to ngdialog.html.

    ngDialog library files can be downloaded from https://github.com/likeastore/ngDialog, or downloaded here: http://cdnjs.com/libraries/ng-dialog. I renamed the file in version 0.4.0 under the link below. The renamed files are as follows:

    1. ngDialog-0.4.0.min.js

    2. ngDialog-0.4.0.min. css

    3. ngDialog-theme-default-0.4.0.min.css

    4. ngDialog-theme-plain-0.4.0.min. css

    API summary learning

    I encountered some doubts when learning, which are recorded below.

    Dialog content template

    To display a dialog box, you must specify the content to be displayed. This is specified via the template attribute. There are three cases of template:

    1. Plain text template embedded in js or html code. At this time, you need to set the plain attribute to true in options at the same time, that is, "plain: true", and then Directly assign a piece of html code to the template, such as template:

      Text in ngDialog

    2. Define the template template in HTML, and specify the id to the template. Assign a value to the template option, such as "template: 'templateId'". The template may look like this:

      > ;
    3. Use an external html fragment (file) as a template, such as "template: 'serverTpl.html'", the serverTpl.html file is on the server.

    Specify the theme

    You can specify the theme through className in options. Currently there are ngdialog-theme-default and ngdialog -theme-plain two themes. These two notes correspond to two css files, which we have introduced through HTML earlier.

    Response to closing and other events

    When the dialog box is closed, some events will be emitted, and developers can listen to these events to get notifications. The specific events are:

    1. ngDialog.opened

    2. ngDialog.closing

    3. ngDialog.closed

    这些事件定义在$rootScope服务里,所以我们的controller构造函数必须依赖$rootScope。比如我们现在的模块定义和controller定义:

    angular.module(‘myApp', [‘ngDialog']). 
    controller(‘myController', function(scope,scope,rootScope, ngDialog){

    在模块定义里注明依赖ngDialog模块,在controller定义里注入了$rootScope和ngDialog。

    如何监听事件,看ngdialog.js代码吧。

    另外我们还可以在options中设置preCloseCallback,指定一个函数,这个函数在对话框取消关闭之前会调用到。https://github.com/likeastore/ngDialog这里有说明。注意,是取消对话框时会调用到,如果确认,不会调到哦。所以,这个preCloseCallback通常在阻止或提醒用户放弃输入时使用,比如用户注册,输入了一些信息,想退,你可以问他是否要真的想放弃。

    指定对话框的controller

    可以通过options设置controller属性来给一个对话框指定控制器。这个控制器可以是内联(inline)的:

        $scope.openInlineController = function () {
          $rootScope.theme = 'ngdialog-theme-plain';
          ngDialog.open({
            template: 'withInlineController',
            controller: ['$scope', '$timeout', function ($scope, $timeout) {
              var counter = 0;
              var timeout;
              function count() {
                $scope.exampleExternalData = 'Counter ' + (counter++);
                timeout = $timeout(count, 450);
              }
              count();
              $scope.$on('$destroy', function () {
                $timeout.cancel(timeout);
              });
            }],
            className: 'ngdialog-theme-plain'
          });
        };

    也可以是在js中定义的。比如我们在js里定义了一个名为“InsideCtrl”的controller,就可以在调用ngDialog.open(options)时在options里设置controller属性:

    $scope.openInsideController = function(){
     ngDialog.open({
      template: "serverTpl.html",
      className: "ngdialog-theme-plain",
      controller: "InsideCtrl"
     });
    };

    具体示例可以参考:https://github.com/likeastore/ngDialog/blob/master/example/index.html。

    确认对话框

    比如让用户确认删除,让用户输入。使用openConfirm(options)就可以创建这样的对话框。ngDialog向$scope注入了两个函数,一个是confirm(value),一个是closeThisDialog(reason),分别用来确认关闭对话框,取消关闭对话框。将它们关联到确认和取消按钮上,就可以确认、取消对话框。

    假如我要让用户输入用户名,可以用ng-model指令将作用域内某个变量和input绑定,在调用confirm时传入绑定的变量,这样就可以在confirm中拿到用户填写的值来做进一步处理。我们的示例中的openConfirmDialog按钮,点击后就弹出一个让用户输入名字的对话框,当用户输入完毕,点击Confirm按钮时,我们可以通过confirm方法的value参数获得用户名输入框的值。

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

    推荐阅读:

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

    Node.js Express安装与使用详细介绍

    The above is the detailed content of How to use Node.js dialog box ngDialog. 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
    The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

    The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

    Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

    Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

    Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

    Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

    JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

    JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

    C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

    C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

    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.

    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

    Dreamweaver Mac version

    Dreamweaver Mac version

    Visual web development tools

    SecLists

    SecLists

    SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

    mPDF

    mPDF

    mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

    SublimeText3 English version

    SublimeText3 English version

    Recommended: Win version, supports code prompts!

    VSCode Windows 64-bit Download

    VSCode Windows 64-bit Download

    A free and powerful IDE editor launched by Microsoft