How to access scope from a compiler function directive?

I have an html directive based on an array sent as an attribute. I cannot access it from the directive compiler function. It works inside the communication function, but I need it inside the compilation, otherwise the new template will not be compiled.

The code is as follows:

<multirangeslider values="ranges" variances="['Master', 'master A', 'master B']"></multirangeslider> 

Directive

 angular.module("vtApp.directives"). directive('multirangeslider', function ($parse, $timeout, $compile) { return { restrict: 'E', replace: true, scope: { values: "=", options: "=", variances: "&" }, compile: function (element, attrs) { var htmlText, variances, values; variances = eval(attrs.variances); values = scope.ranges //scope is undefined values = eval (attrs.variances) //returns string "ranges" values = ??? ///what should I put here? htmlText = '<div></div>'; element.replaceWith(htmlText); return function (scope, element, attrs){ } } } }); 

thanks

+4
source share
1 answer

You will not have access to the scope until the LinkingFunction is returned by the compilation function. The compilation function creates an html template. The area is then combined with the template during LinkingFunction.

I'm not quite sure what you are trying to do, but I would use a standard template or templateUrl object for the binding function, rather than diving into the compilation function. Something like that:

 angular.module("vtApp.directives"). directive('multirangeslider', function ($parse, $timeout, $compile) { return { restrict: 'E', replace: true, template: "<div ng-repeat='val in values'>{{val}}</div>", //Your template code scope: { values: "=", options: "=", variances: "&" }, link: function (scope, element, attrs) { scope.values = eval(attrs.variances) } } }); 

Here you can find more information on how directives are created: https://github.com/angular/angular.js/wiki/Understanding-Directives

+4
source

Source: https://habr.com/ru/post/1479187/


All Articles