search
HomeWeb Front-endJS TutorialAngularJS practice using NgModelController for data binding

Foreword

In Angular applications, the ng-model directive is an indispensable part. It is used to bind the view to data and is an important part of the two-way binding magic. ngModelController is the controller defined in the ng-model directive. This controller contains services for data binding, validation, CSS updates, and value formatting and parsing. It is not used for DOM rendering or listening to DOM events. DOM-related logic should be included in other instructions, and then let these instructions use the data binding function in ngModelController.

Note: This article is not an explanation of the NgModelController documentation, but is more practical. Next, I will lead you through the entire process to implement a custom instruction and use the ng-model attribute to bind data on both sides.

Example

We use a custom directive called timeDruation

as follows

<div ng-app="HelloApp" ng-controller="HelloController">
 <h1 id="自定义指令">自定义指令</h1>
 <time-duration ng-model="test"></time-duration>
 <h1 id="默认指令">默认指令</h1>
 <input ng-model="test">second
</div>


The JS code is as follows,

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


We An example directive can do With such a thing, several common time units can be specified and data can be entered. Finally we will get the corresponding number of seconds. The screenshot of its function is as follows,

AngularJS practice using NgModelController for data binding

Here we specially bind the test variable to our custom instructions and default instructions respectively to observe its effect.

Custom command

Without further ado, let’s take a look at the code

First, let’s look at the template of the command. As can be seen from the picture above, the command contains an input box and a drop-down selection box.

<div class="time-duration">
 <input ng-model=&#39;num&#39;>
 <select ng-model=&#39;unit&#39;>
 <option value="seconds">Seconds</option>
 <option value="minutes">Minutes</option>
 <option value="hours">Hours</option>
 <option value="days">Days</option>
 </select>
</div>


The template is actually very simple, so I won’t go into details here. Let's take a look at the logical part of this instruction.

function TimeDurationDirective() {
 var tpl = &#39;....&#39;; // 指令模板代码就是上面的内容,这里就不复制了。
  
 return {
 restrict: &#39;E&#39;,
 replace: true,
 template: tpl,
 require: &#39;ngModel&#39;,
 scope: {},
 link: function(scope, element, attrs, ngModelController) {
  var multiplierMap = {
  seconds: 1,
  minutes: 60,
  hours: 3600,
  days: 86400
  };
  var multiplierTypes = [&#39;seconds&#39;, &#39;minutes&#39;, &#39;hours&#39;, &#39;days&#39;];
 
  // TODO
 }
 };
}


The link method of the instruction is TODO for the time being. It will be gradually improved later.

Let me first take a look at the definition of this directive, which uses the require statement. Simply put, the function of require is to declare a dependency relationship for this directive, indicating that this directive depends on the controller attribute of another directive.

Here is a brief explanation of the derived usage of require.

We can add a rhetorical quantifier before require, for example,

return {
 require: &#39;^ngModel&#39;
}
 
return {
 require: &#39;?ngModel&#39;
}
 
return {
 require: &#39;?^ngModel&#39;
}


1. The ^ prefix modification means that the parent instruction of the current instruction is allowed to be searched. If the controller of the corresponding instruction cannot be found, an error will be thrown. .

2. ? means turning this require action into an option, which means that if the controller for the corresponding instruction cannot be found, no error will be thrown.

3. Of course, we can also use these two prefix modifications in combination.

Compared with ?ngModel, we use ^ngModel more frequently.

For example

<my-directive ng-model="my-model">
 <other-directive></other-directive>
</my-directive>


At this time, we use require: ^ngModel in other-directive, which will automatically find the controller attribute in the my-directive directive 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 instruction we require. Here is the controller ngModeController of the built-in instruction ngModel.

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


$viewValue and $modelValue

There are two very important properties in ngModelController, one is called $viewValue and the other is called $modeValue.

The official explanation of the meaning of these two is as follows

                                                                                                          using                     $viewValue: Actual string value in the view.

                           If you have any doubts about the official explanation, I will give you my personal explanation here.

$viewView is the value used by the instruction to render the template, and $modelView is the value circulated in the controller. Many times, these two values ​​may be different.

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

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

$formatters and $parses

In addition to the two properties $viewValue and $modelValue, there are two methods for handling them. They are $parses and $formatters respectively.

The former function is to change $viewValue->$modelValue, while the latter function is just the opposite, it is to change $modelValue->$viewValue.

The time-duration instruction and the external controller and its internal operation are as shown below,

AngularJS practice using NgModelController for data binding

     1、在外部控制器中(即这里的HelloApp的controller),我们通过ng-model="test"将test变量传入指令time-duration中,并建立绑定关系。

     2、在指令内部,$modelValue其实就是test值的一份拷贝。

     3、我们通过$formatters()方法将$modelValue转变成$viewValue。

     4、然后调用$render()方法将$viewValue渲染到directive template中。

     5、当我们通过某种途径监控到指令模板中的变量发生变化之后,我们调用$setViewValue()来更新$viewValue。

     6、与(4)相对应,我们通过$parsers方法将$viewValue转化成$modelValue。

     7、当$modelValue发生变化后,则会去更新HelloApp的UI。

完善指令逻辑

按照上面的流程,我们先来将$modelValue转化成$viewValue,然后在指令模板中进行渲染。

// $formatters接受一个数组
// 数组是一系列方法,用于将modelValue转化成viewValue
ngModelController.$formatters.push(function(modelValue) {
 var unit = &#39;minutes&#39;, 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
 };
});

   


最后返回的对象就是$viewValue的value。(当然$viewValue还会有其他的一些属性。)

第二步,我们调用$render方法将$viewValue渲染到指令模板中去。

// $render用于将viewValue渲染到指令的模板中
ngModelController.$render = function() {
 scope.unit = ngModelCtrl.$viewValue.unit;
 scope.num = ngModelCtrl.$viewValue.num;
};

   


第三步,我们通过$watch来监控指令模板中num和unit变量。当其发生变化时,我们需要更新$viewValue。

scope.$watch(&#39;unit + num&#39;, function() {
// $setViewValue用于更新viewValue
 ngModelController.$setViewValue({
 unit: scope.unit,
 num: scope.num
 });
});

   


第四步,我们通过$parsers将$viewValue->$modelValue。

// $parsers接受一个数组
// 数组是一系列方法,用于将viewValue转化成modelValue
ngModelController.$parsers.push(function(viewValue) {
 var unit = viewValue.unit;
 var num = viewValue.num;
 var multiplier;
 
 multiplier = multiplierMap[unit];
 
 return num * multiplier;
});

   

更多AngularJS practice using NgModelController for data binding相关文章请关注PHP中文网!


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

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

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.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)