1.指令方案link
描述:指令方案link是angularJS中提供给自定义指令的一种“专有行为”
操作自定义指令所在范围,包括子元素dom
语法:app.directive('指令名称', function (){
...
...
link:function (scope, element, attrs){...}
});
说明:
(1)scope:如果将整个指令看作是一个controller,那么scope的作用等价于$scope
(2)element:一个包含了指令范围中所有页面元素的数组,每一个元素都是一个dom对象,element[n]表示第n级父元素dom,element[n][1],表示该父元素下的第2个子元素dom
2、可以通过$(elementp[0]).css(),jq方式操作dom,也可通过element[0].style..js方式操作dom
(3)attrs:获取所有的属性集合。attrs.$set('第一级父元素dom标签中的键名','键值')
补充:
在指令内部,需要对scope进行初始化编辑
...
scope:{},
link:function (scope, element, attrs){...}
原因是如果不进行初始化操作,那么scope默认为mainController中的$scope
代码示例:
<head>
<meta charset="utf-8">
<meta name='viewport' content='width=device-width,user-scalable=no,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0'>
<title ng-bind='mainTitle'></title>
<link rel="stylesheet" href="iconfont/iconfont.css">
<link rel="stylesheet" href="css/1.css" type="text/css">
<script src='jq/jquery-3.4.1.js'></script>
<script src="js/bootstrap.min.js"></script>
<script src='js/swiper.jquery.min.js'></script>
<script src="js/swiper.animate1.0.2.min.js"></script>
<link rel="stylesheet" href="css/swiper.min.css">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/animate.min.css">
<script src='js/underscore.js'></script>
<!-- 引入百度地图 -->
<script src='js/angular.js'></script>
<script src='js/angular.route.min.js'></script>
<style>
</style>
</head>
<body >
<div class='frankdiv'></div>
<script>
var app=new angular.module('app',[]);
app.directive('frankdiv', function (){
return {
restrict:'AECM',
template:'<div>'+
'<input type="text" ng-model="msg">'+
'<button ng-click="getMsg(msg)">获取输入内容</button>'+
'</div>',
replace:true,
scope:{},
link:function (scope, element, attrs){
console.log(scope);
console.log(element[0].childNodes[1].nodeName);
console.log(attrs);
element[0].childNodes[1].ondblclick = function (){
console.log('这是一个双击事件');
};
console.log(attrs['class'])
element[0].childNodes[1].style.backgroundColor='red';
//给template中的div,添加style='color:red'属性
attrs.$set('style','color:red')
scope.msg = '';
scope.getMsg = function (tempMsg){
console.log(tempMsg);
}
}
};
});
app.controller('main',['$scope',function($scope){
$scope.mainTitle='自定义指令';
}])
</script>
</body>
</html>