how to obtain $attr manually in angular

狂风中的少年 提交于 2019-12-06 03:49:27

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!