AngularJS practices: Using NgModelController for Data Binding

Source: Internet
Author: User
As we all know, commands in AngularJS are particularly complicated, but they are also a fun part. In this article, we will talk about how to use the controller of ngModel to bind two-way data in our custom commands. This article provides some reference value for you to learn about AngularJS, for more information, see. Preface

In Angular applications, the ng-model command is an indispensable part. It is used to bind a view to data, which is an important part of two-way binding magic. NgModelController is the controller defined in the ng-model command. This controller contains some services for data binding, verification, CSS update, and numerical formatting and parsing. It does not need to perform DOM rendering or listen to DOM events. DOM-related logic should be included in other commands, and these commands should be used to try the data binding function in ngModelController.

Note: This article is not a description of the NgModelController document, but more practical. The following describes how to implement a custom command and use the ng-model attribute to bind data between the two parties.

Example

Our app uses a custom command named timeDruation.

As follows:

Custom commands Default commandsSecond


The JS Code is as follows,

angular.module('HelloApp', []) .directive('timeDuration', TimeDurationDirective); .controller('HelloController', function($scope) { $scope.test = 1; });


The example command can be used to specify several common time units and input data. Finally, we will get the corresponding number of seconds. Its functions are as follows,

Let's take a look at the code below.

The template of the command first. The command contains an input box and a drop-down box.

Seconds Minutes Hours Days


The template is actually very simple. I will not talk about it here. Let's take a look at the logic of this command.

Function TimeDurationDirective () {var tpl = '...'; // the code of the instruction template is the above content, which will not be copied here. Return {restrict: 'E', replace: true, template: tpl, require: 'ngmodel', scope :{}, link: function (scope, element, attrs, ngModelController) {var multiplierMap = {seconds: 1, minutes: 60, hours: 3600, days: 86400}; var multiplierTypes = ['seconds', 'minutes ', 'hours ', 'Days ']; // TODO }};}


We temporarily TODO The link Method of the command. It will be gradually improved later.

Let's take a look at the definition of this command, where the require statement is used. Simply put, require declares a dependency for this directive, indicating that this directive depends on the controller attribute of another instruction.

Here we will briefly describe the derivative usage of require.

We can add rhetorical quantifiers before require, for example,

return { require: '^ngModel'} return { require: '?ngModel'} return { require: '?^ngModel'}


1. ^ prefix modifier indicates that the parent-level command of the current command can be searched. If the controller of the corresponding command cannot be found, an error is thrown.

2 ,? The require action is changed to an option, which means that the controller of the corresponding command cannot be found and no error is thrown.

3. Of course, we can also use these two prefixes together.

Relative? NgModel, ^ ngModel we use more frequently.

For example

  
  
 


In this case, we use require: ^ ngModel in other-directive, which will automatically find the controller attribute in the my-directive command declaration.

Use NgModelController

After we declare require: 'ngmodel', the fourth parameter will be injected into the link method. This parameter is the controller corresponding to the require command. Here is the ngModeController with built-in instructions.

link: function (scope, element, attrs, ngModelCtrl) { // TODO}


$ ViewValue and $ modelValue

NgModelController has two important attributes: $ viewValue and $ modeValue.

The meanings of the two are explained as follows:

$ ViewValue: Actual string value in the view.

$ ModelValue: The value in the model, that the control is bound.

If you have any questions about the official explanation, I will give you a personal explanation here.

$ ViewView is the value used by the instruction rendering template, while $ modelView is the value circulating in the controller. In many cases, these two values may be different.

For example, if you display a date on the page, it may be "Oct. 20 2015 ", but the value of this string in the Controller may be an example of a Javascript Date object.

For another example, in our time-duration example, $ viewValue actually refers to the combination of num and unit in the instruction template, $ modelValue is the value corresponding to the test variable in HelloAppController.

$ Formatters and $ parses

In addition to the $ viewValue and $ modelValue attributes, there are two methods for processing them. They are $ parses and $ formatters.

The former is used to convert $ viewValue-> $ modelValue. The latter is used to convert $ modelValue-> $ viewValue.

Time-duration commands and external controllers as well as their internal operations such,

According to the above process, we first convert $ modelValue to $ viewValue, and then render it in the instruction template.

// $ Formatters accepts an array // an array is a series of methods used to convert modelValue to viewValuengModelController. $ formatters. push (function (modelValue) {var unit = 'minutes ', num = 0, I, unitName; modelValue = parseInt (modelValue | 0); for (I = multiplierTypes. length-1; I> = 0; I --) {unitName = multiplierTypes [I]; if (modelValue % multiplierMap [unitName] = 0) {unit = unitName; break ;}} if (modelValue) {num = modelValue/multiplierMap [unit];} return {unit: unit, num: num };});


The final returned object is the value of $ viewValue. (Of course, $ viewValue has other attributes .)

Step 2: Call the $ render method to render $ viewValue to the instruction template.

// $ Render is used to render viewValue to the instruction template ngModelController. $ render = function () {scope. unit = ngModelCtrl. $ viewValue. unit; scope. num = ngModelCtrl. $ viewValue. num ;};


Step 3: use $ watch to monitor the num and unit variables in the instruction template. When it changes, we need to update $ viewValue.

Scope. $ watch ('unit + num', function () {// $ setViewValue is used to update viewValue ngModelController. $ setViewValue ({unit: scope. unit, num: scope. num });});


Step 4: Use $ parsers to convert $ viewValue-> $ modelValue.

// $ Parsers accepts an array // an array is a series of methods used to convert viewValue to modelValuengModelController. $ parsers. push (function (viewValue) {var unit = viewValue. unit; var num = viewValue. num; var multiplier; multiplier = multiplierMap [unit]; return num * multiplier ;});

For more AngularJS practices, use NgModelController to bind data. For more information, see PHP!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.