標籤:
(一)Hello Angular
index.html
<!DOCTYPE html><html ng-app> <head> <title>Test AngularJS</title> <meta charset="utf-8"> </head> <body> <div ng-controller="HelloAngular"> <p>{{greeting.text}},Angular</p> </div> </body> <script src="js/angular.min.js"></script> <script src="controller/HelloAngular.js"></script></html>
HelloAngular.js
function HelloAngular($scope) { $scope.greeting = { text: ‘Hello‘ };}
angular.min.js
這個檔案在網上隨便那裡下個吧,比如新浪的前端庫地址:http://lib.sinaapp.com/js/angular.js/angular-1.1.0/angular.min.js
min是壓縮後的檔案,在indexl中直接引入連結也可,但還是下載到本地方便呢
在瀏覽器開啟index.hml,看看輸出吧~
PS:上面的index.html中的使用ng-controller的方式存在一點點問題,就是快速重新整理網頁或者是很多資料的時候會有短暫的顯示{{greeting.text}},我們可以通過如下的方式解決。
<p>{{greeting.text}},Angular</p>
把index.html中的上面那句換成
<p><span ng-bind="greeting.text"></span>,Angular</p>
在網頁沒載入好的情況下會顯示“,Angular”,而不是“{{greeting.text}},Angular”
(二)錯誤的控制器使用方法
不要使用通用控制器,進行繼承或調用等,每個控制器只負責一小部分的邏輯即可
如下的控制器和首頁引用代碼是不建議使用的範例:
HTML
<div ng-controller="CommonController"> <div ng-controller="Controller1"> <p>{{greeting.text}}, Angular</p> <button ng-click="test1()">Click1</button> </div> <div ng-controller="Controller2"> <p>{{greeting.text}}, Angular</p> <button ng-click="test2()">Click2</button> </div> <button ng-click="common()">Common</button></div>
Controller
function CommonController($scope) { $scope.common = function() { alert("Common"); };}function Controller1($scope) { $scope.greeing = { text: ‘Hello1‘ }; $scope.test1 = function() { alert("Test1"); };}function Controller2($scope) { $scope.greeing = { text: ‘Hello2‘ }; $scope.test2 = function() { alert("Test2"); };}
雖然可以正常的工作,但是建議把公用的代碼抽象成“服務”來實現。
(三)ng-model 的時時顯示
<!DOCTYPE html><html ng-app> <head> <title>Test AngularJS</title> <meta charset="utf-8"> </head> <body> <div> <input ng-model="qq" /> <p>{{ qq }}</p> </div> </body> <script src="js/angular.min.js"></script></html>
上面就是效果,輸入什麼下面就同步的顯示什麼
(四)ng-replat
下面的程式碼片段是一個簡單的迴圈
<div><ol> <li ng-repeat="name in names"> {{name}} from {{department}} </li></ol></div>
可以定義全域的rootScope,這是全域可用的
function CreetCtrl($scope, $rootScope) { $rootScope.department = ‘Angular‘;}function ListCtrl ($scope) { $scope.names = [‘David‘, ‘Dong‘, ‘Sellea‘];}
(五)路由,模組,依賴注入
(一)中的控制器定義的是全域變數,這樣做是不好的,而且也不模組化
var helloModule = angular.module(‘HelloAngular‘, []);helloModule.controller(‘helloNgCtrl‘, [‘$scope‘, function($scope){ $scope.greeting = { text: ‘Hello‘ };}]);
路由內建的也可以,不過使用angular-ui-router這個模組會更好
依賴注入的功能使得AngularJS可以方便的引入模組,在引入最小數量模組的同時實現功能
Hello World會寫後,接下來學習些雙向資料繫結什麼的,這些概念都是第一次聽說,AngularJS真是個蠻有趣的東西
AngularJS學習筆記(一)——一些基本知識