双向绑定是angularjs亮点之一,在前面的《angularjs培训之helloworld》篇中大概介绍了下双向绑定,现在我们“旧事重提”,先看下下面的代码片段:
view中:
controller中对应的方法:
scope.set=function()$scope.userName2=‘Eason′; scope. watch(‘userName2′,function()alert(‘ng−modeluserName2hasbeenchanged,nowis:′+$scope.userName2););我们要实现的功能是:点击按钮给model名为“userName2”的input框设置为字符串“Eason”,使用 watch注册一个观察事件,当模型userName2的值发生变化时,会触发注册的回调方法,打印出该模型中的值。
wKioL1Q2L0HyP3YwAADe4uPQjy0831.jpg
有了这个图双向绑定好理解多了吧。内部的实现机制后续咱们介绍。
有了按钮怎么给按钮注册呢?在angularjs中我们可以使用内置的指令ng-click来绑定事件,即上面代码中的 ng-click=”set()”,在controller中就可以使用 scope.set的形式实现方法。ng-click其实对html原始click事件的封装,其实不止是click事件,原生的事件向focus,blur,change事件都可以在angularjs中官方API中找到对应的方法。具体的可以戳这里http://docs.angularjs.cn/api/ng/directive
在上讲中我们通过实例看了下scope的嵌套,现在如果我们想要一个特定的功能能横跨多个scope,需要提供一个有用的方法使得可以在任意两个controller之间通信,该怎么做呢?其实在angularjs中提供了沿着scope作用域链向上或者向下发送消息来通信,即 emit, broadcast
先看下图:
wKiom1Q2Pu-CYALSAABmlT2Q_e4935.jpg
emit从当前scope开始向上发送请求,该请求到达 rootScope为止,
$broadcast从当前scope开始向下发送请求,
$emit的基本用法:
scope. emit(‘event name’,argument);
scope. broadcast(‘event name’,argument);
第一个参数为事件名称,第二个名字即为要传递的数据。
现在有了向上和向下传递事件的方法了,该怎么接受对应的事件名称呢?我们可以使用$on监听。如下:
scope. on(‘event name’,function(evt) {
});
下面看一个完整的例子:
function innerCtrl($scope){
$scope.$emit(‘someEvent’, [1,2,3]);
}
function outerCtrl($scope){
$scope.$on(‘someEvent’, function(mass) {console.log(mass)});
}
通过运行代码,我们在控制台能看到数组的值。
Event 对象还有很多熟悉和方法,我们大概浏览下:
targetScope,
currentScope,
name,
stopPropagation,
preventDefault,
defaultPrevented :Calling preventDefault() sets defaultPrevented to true
Angularjs也提供了监听公共事件状态的event,例如(之摘录了一部分):
includeContentLoaded:The includeContentLoaded event fires from the ngInclude directive when the ngInclude content is reloaded.
locationChangeSuccess:The locationChangeSuccess event is broadcasted from the rootScopeifandonlyifwehavenotpreventedthe locationChangeStart event when the location of the browser changes successfully
$routeChangeSuccess:
$destroy
好了,这次的介绍到此为止了,有问题请留言,谢谢!