Angular 通过指令操作DOM

angular是不鼓励自己操作DOM的,但是你想,也可以。官方建议通过指令操作,可以通过自带的指令,当然最强大的是可以自己定义指令。

对于services, 我们可以通过module 对象的 API directive() 函数来定义指令:

var appModule = angular. module(' appModule' , [ . . . ] );
appModule. directive(' directiveNam e' , directiveFunction);

directiveFunction应该是一个工厂函数,不过太复杂了,我们来个简单的:

比如我们想让一个链接元素获得焦点,我们可以这么写:

var appModule = angular. module(' app' , [ ] );
appModule. directive(' ngbkFocus' , function() {
return {
link: function(scope, element , attrs, controller) {
element [0] . focus();
}
};
});

这里我们定义了link函数然后作为指令的配置对象返回。在link函数里,我们将元素聚焦。

模板中这样使用:

index.html
<html lang='en' ng-app='app' >
<body ng-controller="SomeController">
<button ng-click="clickUnfocused()">
Not focused
</ button>
<button ngbk-focus ng-click="clickFocused()">
I ' m very focused!
</ button>
<div>{{message. text }}</ di v>
</ body>
</ html >

controllers .js
function SomeController($scope) {
$scope. message = { text : ' nothing clicked yet ' };
$scope. clickUnfocused = function() {
$scope. message. text = ' unfocused button clicked' ;
};
$scope. clickFocused = function {
$scope. message. text = ' focus button clicked' ;
}
}
var appModule = angular. modul e(' app' , [ ' di rect i ves' ] );

这样,当页面加载时,用户会看到标记"I’m very focused!"按钮获得焦点高亮。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值