您的位置:首页 > Web前端 > AngularJS

angular指令中link函数 参数实例详解

2016-12-22 18:18 681 查看
* html代码 *

<!doctype html>
<html ng-app="MyModule">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/bootstrap-3.0.0/css/bootstrap.css">
</head>
<body>
<div ng-controller="MyCtrl">
<greeting greet="sayHello(name)"></greeting>
<!--
<greeting greet="sayHello2(name)"></greeting>
-->
<greeting greet="sayHello(name)" class="testclass"></greeting>
</div>
</body>
<script src="js/angular-1.3.0.js"></script>
<script src="testtest.js"></script>
</html>


* js 代码 *

var MyModule = angular.module('MyModule',[]);
MyModule.controller('MyCtrl',function($scope){
$scope.sayHello = function(name){
alert("hello "+name);
}
});
MyModule.directive('greeting', function () {
return{
restrict:'AE',
scope:{
say:'&greet'
},
//template不操作对象,只是描述了指令标签的html内容,可以给内部的dom绑定方法
template:'<div class="testclass" id="testid"><input class="" ng-model="input1"><br/><button ng-click="say({name:input1})">click</button><br/></div>',
link:function(scope,ele,attr){
scope.input1 = "11111111";
scope.input2 = "2222222222";
//ele指的是html中的指令标签的对象,可以理解成$('directive对象'),类似jquery的选择器。
//这里给element绑定方法或者添加clss等,只能针对整个指令dom
ele.addClass('btn btn-primary');//对指令对象添加新的class
ele.bind("mouseenter", function() {//对指令对象添加监听方法
console.log(scope.input2);
});
console.log(attr.class);//获取指令dom上面的属性名称。输出为testclass
console.log(attr.greet);//获取指令dom上面的属性名称。输出为sayHello(name)
//因为通过scope传了属性值greet,所以attr上greet属性是已经存在的属性。
}
}
});


* 页面截图 *

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  angular