Home > Web Front-end > JS Tutorial > AngularJS practice using NgModelController for data binding

AngularJS practice using NgModelController for data binding

高洛峰
Release: 2016-12-24 10:36:19
Original
1536 people have browsed it

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>自定义指令</h1>
 <time-duration ng-model="test"></time-duration>
 <h1>默认指令</h1>
 <input ng-model="test">second
</div>
Copy after login


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;
 });
Copy after login


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>
Copy after login


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
 }
 };
}
Copy after login


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;
}
Copy after login


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>
Copy after login


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
}
Copy after login


$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
 };
});
Copy after login


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

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

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


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

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


第四步,我们通过$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;
});
Copy after login

   

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


source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template