如何以角度手动获取$ attr(how to obtain $attr manually in angular)

我想知道如何从linkFn回调手动获取属性。

例如,如果我想要范围,我会,

angular.element(element).scope()

调节器

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

怎么样的attr。

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.

最满意答案

在父控制器中,我认为您可以在首次将其分配给指令中的scope属性后访问该属性对象:

<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);
}
 

小提琴

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

更多推荐