AngularJs 指令 - 绑定子元素
AngularJs directive - bind child element
指令
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
returns :
<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
函数?
这是您需要的代码,
<!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>
请运行摘录。
您可以在 directive
中使用 element.find("img");
,然后在其上使用 .bind
语句来附加事件。
希望对您有所帮助!
指令
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
returns :
<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
函数?
这是您需要的代码,
<!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>
请运行摘录。
您可以在 directive
中使用 element.find("img");
,然后在其上使用 .bind
语句来附加事件。
希望对您有所帮助!