AngularJs指令 - 绑定子元素

时间:2017-01-18 07:33:38

标签: javascript angularjs angular-directive angular-directive-link

指令

app.directive('mcAvatar', function() {
    return {
        restrict: 'E',
        scope: {
            width: '=width',
            src: '@src'
        },
        templateUrl: 'directives/mc-avatar/mc-avatar.html',
        link: function (scope, element, attrs) {
            console.log(element[0])
        }
    };
});

模板

<img width="{{ width }}" src="{{ src }}" alt="" class="mc-avatar-round">

用法

<mc-avatar width="50" src="http://lorempixel.com/320/320/cats"></mc-avatar>

指令中link函数内的element返回:

<mc-avatar width="50" src="http://lorempixel.com/320/320/cats" class="ng-isolate-scope">
    <img width="50" src="http://lorempixel.com/320/320/cats" alt="" class="mc-avatar-round">
</mc-avatar>

仅为mg-avatar提供上下文。如何在此处访问img元素,以便我可以使用bind函数?

2 个答案:

答案 0 :(得分:1)

这是您需要的代码,

&#13;
&#13;
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myApp">

<mc-avatar width="50" src="http://lorempixel.com/320/320/cats"></mc-avatar>

<script>
var app = angular.module("myApp", []);
app.directive('mcAvatar', function() {
    return {
        restrict: 'E',
        replace: false,
        scope: {
            width: '=width',
            src: '@src'
        },
        
        template: '<img width="{{ width }}" src="{{ src }}" alt="" class="mc-avatar-round">',
        link: function (scope, element, attrs) {
            console.log(element.find("img"))
        }
    };
});
</script>

</body>
</html>
&#13;
&#13;
&#13;

请运行代码段。

Here is a working Demo

答案 1 :(得分:1)

您可以在element.find("img");中使用directive,然后在其上使用.bind语句附加活动。

希望这有帮助!