Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to obtain $attr manually in angular

I want to know how I might manually obtain the attribute from the linkFn call back.

e.g. if I want scope, I do,

angular.element(element).scope()

controller

angular.element(element).controller('ngModel')

how about for attr.

like image 778
user2167582 Avatar asked Jan 25 '26 13:01

user2167582


2 Answers

In the parent controller I suppose you could access the attributes object after first assigning it to a scope property in the directive:

<div ng-controller="MyCtrl">
    <div my-directive attr1="one">see console log</div>
</div>
app.directive('myDirective', function() {
    return {
        link: function(scope, element, attrs) {
            scope.attrs = attrs
        },
    }
});

function MyCtrl($scope, $timeout) {
    $timeout(function() {
        console.log($scope.attrs);
    }, 1000);
}

fiddle

like image 146
Mark Rajcok Avatar answered Jan 28 '26 06:01

Mark Rajcok


Use instances of the $compile and $rootScope services, call $digest, then access attr and attributes:

/* template string */
var html = "<div>ID: {{$id}}</div>";
/* template element creation */
var template = angular.element(html);
/* compile instance */
var compiler = angular.injector(["ng"]).get("$compile");
/* rootScope instance */ 
var scope = angular.injector(["ng"]).get("$rootScope");
/* template compilation */
var linker = compiler(template)(scope);
/* digest cycling */
scope.$digest();
/* scope linking */
var result = linker(scope)[0];
/* attr method */
linker.attr("class");
/* attribute property */
result.attributes;

References

  • NPM: Angular Node

  • AngularJS Source: injector.js

  • Tao of Code: Studying the Angular injector - the twin injectors

  • The life and times of the angular provider

  • AngularJS API: $compile.directive.Attributes

like image 25
Paul Sweatte Avatar answered Jan 28 '26 06:01

Paul Sweatte