参数
相关参数
- controller在组件中是一个函数,他有四个参数,分别是
$scope、$element、$attrs、$transclude
- 我们在使用中可以打印这四个参数(注意
$transclude
使用的时候必须开启transclude:true
) - html
<hello-world name1="hello" name2="world"></hello-world>
- js
controller:function($scope,$element,$attrs,$transclude){
console.log("$scope",$scope);
console.log("$element",$element);
console.log("$attrs",$attrs);
console.log("$transclude",$transclude);
}
- 打印的效果图
参数的作用
通过打印我们大致可以总结一下规律
- $scope:指令当前的作用域,所有在scope上绑定的属性方法,在指令中都可以随意使用
- $element:使用指令的当前元素
- $attr:使用指令当前元素上的属性
- $transclude:我们发现他是一个函数,它主要是用于克隆和操作dom,但是我们并不推荐用它来操作dom
$transclude
完成需求,想组件中添加一个dom标签
代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="https://cdn.staticfile.org/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<h1>{{indexName}}</h1>
<!-- 自定义组件 -->
<hello-world name1="hello" name2="world"></hello-world>
</div>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope) {
$scope.indexName = "主页";
$scope.childName = "父组件自定义组件名称"
});
app.directive("helloWorld",function(){
return {
restrict:'ECMA',
template:`
<div>
<h2>{{childName}}</h2>
<div id="box"></div>
</div>
`,
transclude:true,
controller:function($scope,$element,$attrs,$transclude){
$transclude(function(clone){
var ele = angular.element("<div>我是新生儿</div>")
console.log("clone",clone);
console.log("ele",ele);
ele.attr("id","child")
var boxEle = document.getElementById("box")
boxEle.append(ele[0])
})
}
}
})
</script>
</body>
</html>