This article mainly introduces the attributes of angularjs custom ng-model labels, for more information, see add ng-model to non-input elements to implement bidirectional data binding to reduce redundant code.
For example, the contenteditable attribute is used on my page to implement p elements that can be directly compiled by users.
Html:
Output new data
However, binding ng-model directly cannot obtain data. Therefore, you need to add custom attributes to 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 ('contenteditable', function () {// attributes of the custom ngModel can be used in other elements such as p. return {restrict: 'A', // use require as an attribute: '? Ngmodel', // function link: function (scope, element, attrs, ngModel) {if (! NgModel) {return;} // do nothing if no ng-model // Specify how UI shocould 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
Behind // If strip-br attribute is provided then we strip this out if (attrs. stripBr & html ='
') {Html = '';} ngModel. $ setViewValue (html) ;}};}) script
The parameter categories are as follows:
Partial parameter explanation
Restrict:
(String) an optional parameter that specifies the form in which the command is declared in the DOM;
Values: E (element), A (attribute), C (class), and M (comment). The default value is;
E (element ):
A (attribute ):
C (class ):
M (comment): <-- directive: directiveName expression -->
2. require
A string represents the name of another instruction. It will be the fourth parameter of the link function.
For specific usage, we can give an example.
Suppose we want to write two commands now. There are many coincidence methods in the link function of the two commands (described later in the link function,
At this time, we can write these repeated methods in the controller of the Third Command (as mentioned above, the controller is often used to provide reusable behavior between commands)
Then in the two commands, the require command with the controller field (the Third Command ),
The fourth parameter of the link function can reference these coincidence methods.