您必须使用链接来查看以下示例:
假设这是你的 html 代码:
<section ng-app="myApp" ng-controller="MainCtrl">
<my-angular-component></my-angular-component>
</section>
这是Js文件:
var myApp = angular.module('myApp', []);
function MainCtrl($scope) {
}
//Directive that returns an element which adds buttons on click which show an alert on click
myApp.directive("myAngularComponent", function(){
return {
restrict: "E",
template: "<span addbuttons >Click to add buttons</span>",
link: function(scope, elem, attrs,$compile) {
elem.addClass('myCss');
$compile(element)(scope);
}
}
});
这是 CSS:
.myCss{
background:green;
}
注意指令中使用的链接函数。需要三个
参数:范围、元素、属性
范围
– 传递给指令的范围。在这种情况下,它与父控制器范围相同。
元素
– 应用指令的 jQLite(jQuery 的子集)包装元素。如果您在包含 AngularJS 之前在 HTML 中包含了 jQuery,这将变成 jQuery 包装而不是 jQLite。由于该元素已经用 jQuery/jQLite 包装,因此无需再次将其包装在 $() 中以进行 DOM 操作。
属性
- 表示附加到应用指令的元素的规范化属性的对象。例如,您可以在 HTML 中附加属性,例如:并在链接函数中以 attrs.someAttribute 访问它。
查看示例听到:http://jsfiddle.net/kevalbhatt18/vgpmoca3/1/