指令
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
函数?
答案 0 :(得分:1)
这是您需要的代码,
<!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;
请运行代码段。
答案 1 :(得分:1)
您可以在element.find("img");
中使用directive
,然后在其上使用.bind
语句附加活动。
希望这有帮助!