標籤:成功 alert 對象 其他 名稱 class 指令 title remember
<!DOCTYPE html><html lang="zh-CN" ng-app="app"><head> <meta charset="utf-8"> <title>繫結原則</title> <link rel="stylesheet" href="../bootstrap.min.css"></head><body> <h4> AngularJS提供了幾種方法能夠將指令內部的隔離範圍,同指令外部的範圍進行資料繫結。 </h4> 為了讓新的指令範圍可以訪問當前本地範圍中的變數,需要使用下面三種別名中的一種(以下為官方的解釋): <ol> <!--本地範圍屬性:使用@符號將本地範圍同DOM屬性的值進行綁定。指令內部範圍可以使用外部範圍的變數。--> <li>@ (or @attr)</li> <!--雙向繫結:通過=可以將本地範圍上的屬性同父級範圍上的屬性進行雙向的資料繫結。 就像普通的資料繫結一樣,區域屬性會反映出父資料模型中所發生的改變。 --> <li>= (or =attr)</li> <!--父級範圍綁定 通過&符號可以對父級範圍進行綁定,以便在其中運行函數。意味著對這個值進行設定時會產生一個指向父級範圍的封裝函數。 要使調用帶有一個參數的父方法,我們需要傳遞一個對象,這個對象的鍵是參數的名稱,值 是要傳遞給參數的內容。--> <li>& (or &attr)</li> </ol> <div style="border: 1px solid red;width: 400px;height: 200px;" ng-controller="ParentController"> <p style="color: orange;">請認真記住以下輸入框中的提示文字</p> 記住了?<input type="checkbox" ng-model="isRemember"> <p ng-show="isRemember"> <input type="text" ng-model="someVal" placeholder="隨意輸入幾個值"> 並試著改變下面兩個input的值 </p> <div ng-show="!isRemember || someVal" my-directive one-val="{{someVal}}" two-val="someVal" three-val="parentFun(‘哈哈‘)"></div> </div> <script src="../angular.min.js"></script> <script> angular.module(‘app‘, []) .directive(‘myDirective‘, function() { return { restrict: ‘A‘, replace: true, scope: { oneVal: ‘@oneVal‘, // 相當於“值複製” twoVal: ‘=twoVal‘, // 相當於“引用複製” threeVal: ‘&threeVal‘ // 綁定父範圍中的方法 }, template: ‘<div>‘+ ‘<input type="text" ng-model="oneVal" placeholder="@ 改變我其他不受影響">‘+ ‘<input type="text" ng-model="twoVal" placeholder="= 要是動我其他都得變">‘+ ‘<input type="button" ng-click="threeVal()" value="$ 點我試試">‘+ ‘</div>‘ } }) .controller(‘ParentController‘, function($scope) { $scope.parentFun = function(s) { alert("我成功綁定了父級範圍中的函數!" + s); } }) </script></body></html>
以上執行個體可以直接運行,動手跑跑更有意思哦!
angularjs中的繫結原則“@”,“=”,“&”執行個體