標籤:anguarls event data-bind
雙向繫結是angularjs亮點之一,在前面的《angularjs培訓之helloworld》篇中大概介紹了下雙向繫結,現在我們“舊事重提”,先看下下面的程式碼片段:
view中:
<input type=‘button‘ ng-click="set()" value="set Value"> <input type="text" ng-model=‘userName2‘>
controller中對應的方法:
$scope.set = function(){ $scope.userName2 = ‘Eason‘; } $scope.$watch(‘userName2‘,function(){ alert(‘ng-model userName2 has been changed, now is :‘ + $scope.userName2); });
我們要實現的功能是:點擊按鈕給model名為“userName2”的input框設定為字串“Eason”,使用$watch註冊一個觀察事件,當模型userName2的值發生變化時,會觸發註冊的回調方法,列印出該模型中的值。
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M01/4B/F8/wKioL1Q2L0HyP3YwAADe4uPQjy0831.jpg" title="Two_Way_Data_Binding.png" alt="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
先看:
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M00/4B/F7/wKiom1Q2Pu-CYALSAABmlT2Q_e4935.jpg" title="QQ20141009155247.png" alt="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 $rootScope if and only if we have not prevented the $locationChangeStart event when the location of the browser changes successfully
$routeChangeSuccess:
$destroy
好了,這次的介紹到此為止了,有問題請留言,謝謝!
本文出自 “Eason's hcc” 部落格,請務必保留此出處http://hcc0926.blog.51cto.com/172833/1561827
angularjs培訓之重新理解雙向繫結和事件詳解