<field title="" type="select" ng-model="selectedColor" options="color.id as color.name for color in colors"></field>
selectedColor
and colors
variables from the example are the scope variables in which we used the directive. We specifically indicated them through attributes so that the directive could access them. angular.module('directives').directive('field', function () { return { // - restrict: 'E', // , scope: { ngModel: "=", title: "@", type: "@", options: "@" }, // templateUrl: '/tpl/fields/select.html', });
<div class="field"> <label>{{title}}</label> <select ng-model="ngModel" ng-options="{{options}}"></select> </div>
Live: codepen.io/Dzorogh/pen/umCKG?editors=101
<field title="" type="select" ng-model="selectedColor" options="color.id as color.name for color in colors"> <label></label> <select ng:options="color.id as color.name for color in colors" ng:model="ngModel"></select> </field>
ngModel, type, title, options
) that we specified to the directive parameter will be added to our isolated scope and tied to external variables.colors
to those variables. And rightly so, the directive, of course, should not know what kind of array we want to use there. We have already indicated that we are using this array by writing it in the options attribute. .directive('field', function() { // angularjs var NG_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+(.*?)(?:\s+track\s+by\s+(.*?))?$/; }; return { restrict: 'E', scope: { ngModel: "=", type: "@", title: "@", options: "@" }, // "" transclude: true, templateUrl: '/fields/select.html', // $transclude 5 . link: function (scope, element, attrs, controller, $transclude) { if (scope.type == 'select') { // var parsedOptions = attrs.options.match(NG_OPTIONS_REGEXP); // ( | ) var optionsArray = /^(.*) \|/.exec(parsedOptions[7]) || parsedOptions[7]; // optionsArray - ( ) , . // , Scope // (, ) . $transclude(function (clone, $outerScope) { scope[optionsArray] = $outerScope[optionsArray]; }); } } } });
The final version in CodePen: codepen.io/Dzorogh/pen/gBbyI
Source: https://habr.com/ru/post/228863/
All Articles