Angularjs the properties of a custom Ng-model label _angularjs

Source: Internet
Author: User


Sometimes we need to add ng-model for non-input type elements to achieve two-way data binding, thus reducing redundant code, then you can try the way



For example: I use the contenteditable attribute on my page to implement a DIV element that the user can compile directly



Html:


<style>
.text{
margin:0 auto;
Width:100px;
Height:50px;
border:1px solid red;
}
</style>
</head>
<body>
<div ng-controller="selectController">
<div ng-repeat="pop in citylist">
<div class="text" contenteditable="true" ng-model="pop.pop"></div>
</div>
< button ng Click = "cs()" > output new data < / button >
</div>
</body>



But the direct binding Ng-model is definitely not going to get the data, then you need to add custom attributes for it, as shown below.



Js:


<script>
var app = angular.module('app', []);
app.controller('selectController', function ($scope) {
$scope. CityList = [{ID: 1, Pop: "Beijing"}, {ID: 1, Pop: "Shanghai"}, {ID: 1, Pop: "Guangzhou"}];
$scope.p={};
$scope.cs=function(){
console.log($scope.citylist);
}
}). Directive ('contentable ', function() {/ / the attribute of a custom ngmodel can be used in div and other elements
Return {
Restrict: 'a', / / used as attribute
Require: '? Ngmodel', / / function replaced by this instruction
link: function(scope, element, attrs, ngModel) {
if (!ngModel) {
Return;
} // do nothing if no ng-model
// Specify how UI should be updated
ngModel.$render = function() {
element.html(ngModel.$viewValue || '');
}
// Listen for change events to enable binding
element.on('blur keyup change', function() {
scope.$apply(readViewText);
};
// No need to initialize, AngularJS will initialize the text based on ng-model attribute
// Write data to the model
function readViewText() {
var html = element.html();
// When we clear the content editable the browser leaves a <br> behind
// If strip-br attribute is provided then we strip this out
if (attrs.stripBr &amp;&amp; html === '<br>') {
HTML = '';
}
ngModel.$setViewValue(html);
}
}
}
}
</script>


The parameter categories are as follows:






Partial parameter interpretation



Restrict



(string) An optional parameter that indicates in what form the instruction is declared in the DOM;



Values are: E (Element), a (attribute), C (Class), M (note), where the default value is a;



E (Element):<directivename></directivename>
A (attribute): <div directivename= ' expression ' ></div>
C (Class): <div class= ' directivename ' ></div>
M (note): <--directive:directivename expression-->



2.require



The string represents the name of another instruction, which will be the fourth parameter of the link function



We can give an example to illustrate the specific usage



Let's say we're writing two instructions, and there's a lot of overlap in the link-link function in two directives (as the link function says).



At this point we can write these repetitive methods in the controller of the third instruction (it also mentions that controller is often used to provide the reuse behavior between instructions).



Then, in these two instructions, require the instruction with the Controller field (the third instruction),



Finally, we can refer to these coincident methods by using the fourth parameter of link function.


<!doctype html>
<html ng-app="myApp">
<head>
 <script src="http://cdn.staticfile.org/angular.js/1.2.10/angular.min.js"></script>
</head>
<body>
 <outer-directive>
   <inner-directive></inner-directive>
   <inner-directive2></inner-directive2>
 </outer-directive>
 <script>
  var app = angular.module('myApp', []);
  app.directive('outerDirective', function() {
     return {
        scope: {},
        restrict: 'AE',
        controller: function($scope) {   
         this.say = function(someDirective) { 
           console.log('Got:' + someDirective.message);
         };
        }
      };
  });
  app.directive('innerDirective', function() {
     return {
        scope: {},
        restrict: 'AE',
        require: '^outerDirective',
        link: function(scope, elem, attrs, controllerInstance) {
            scope.message = "Hi,leifeng";
            controllerInstance.say(scope);
        }
     };
  });
  app.directive('innerDirective2', function() {
     return {
        scope: {},
        restrict: 'AE',
        require: '^outerDirective',
        link: function(scope, elem, attrs, controllerInstance) {
            scope.message = "Hi,shushu";
            controllerInstance.say(scope);
        }
     };
  });
 </script>
</body>
</html>


The instruction innerdirective and instruction InnerDirective2 in the example above are used to define the method defined in the controller of the instruction Outerdirective.



It is further explained that the controller in the instruction is used to communicate between different instructions.



In addition, we can add one of the following prefixes to the Require parameter value, which will change the behavior of the lookup controller:



(1) without a prefix, the instruction will be found in the controller provided by itself, and if no controller is found, an error will be thrown



(2)? If the required controller is not found in the current instruction, NULL is passed to the fourth parameter of the link join function



(3) ^ If the required controller is not found in the current instruction, the controller of the parent element is looked up



(4)? ^ combination


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.