深入淺析AngularJS和DataModel_AngularJS

來源:互聯網
上載者:User

AngularJS 簡介

AngularJS 是一個 JavaScript 架構。它可通過 <script> 標籤添加到 HTML 頁面。

AngularJS 通過 指令 擴充了 HTML,且通過 運算式 綁定資料到 HTML。

什麼是 AngularJS?

AngularJS 使得開發現代的單一頁面應用程式(SPAs:Single Page Applications)變得更加容易。

AngularJS 把應用程式資料綁定到 HTML 元素。

AngularJS 可以複製和重複 HTML 元素。

AngularJS 可以隱藏和顯示 HTML 元素。

AngularJS 可以在 HTML 元素"背後"添加代碼。

AngularJS 支援輸入驗證。

通常,在AngularJS中使用JSON作為儲存資料的模型。我們可能這樣在controller中寫model:

app.controller('BookController',['$scope',function($scope){$scope.book = {id:1,name:'',author:'',stores:[{id:1, name:'', quantity:2},{id:2, name:'', quantity:2},...]};}])

在視圖中也許這樣用到這個model:

<div ng-controller="BookController"><span ng-bind="book.id"></span><input type="text" ng-model="book.name"/><input type="text" ng-model="book.author"/></div> 

當我們需要從服務端擷取資料的時候,可能這樣寫:

app.controller('BookController',['$scope', '$http', function($scope, $http){var bookId = 1;$http.get('api/books'+bookId).success(function(bookData){$scope.book = bookData;})$scope.deleteBook = function(){$http.delete('api/books/' + bookId);}$scope.updateBook = function(){$http.put('api/books/'+bookId, $scope.book);}$scope.getBookImageUrl = function(width, height){return 'our/iamge/service' +bookId + '/width/height';}$scope.isAvailable = function(){if(!$scope.book.stores || $scope.book.stores.length === 0){return false;}reutrn $scope.book.stores.some(function(store){return store.quantity > 0;})}}]) 

在視圖中可能這樣使用:

<div ng-controller="BookController"><div ng-style="{backgroundImage: 'url('+getBookImageUrl(100,100)+')'}"></div><span ng-bind="book.id"></span?<input type="text" ng-model="book.name"/><input type="text" ng-model="book.author"/>is available: <span ng-bind="isAvailable() ? 'Yes' : 'No'"></span><button ng-click="deleteBook()">Delete</button><button ng-click="updateBook">Update</button></div> 

以上,JSON格式的model只能在BookController中使用,如何在其他controller中也可以使用呢?
--通過factory方式

app.factory('Book', ['$http', function($http){function Book(bookData){if(bookData){this.setData(bookData);}}Book.prototype = {setData: function(bookData){angular.extend(this, bookData);},load: function(id){var scope = this;$http.get('api/books/' + bookId).success(function(bookData){scope.setData(bookData);})},delete: function(bookId){$http.delete('api/books/' + bookId);},update: function(bookId){$http.put('api/books/' + bookId, this);},getImageUrl: function(width, height){return 'our/image/service/' + this.book.id + '/' + width + '/' + height;},isAvailable: funciton(){if(!this.book.stores || this.book.stores.length === 0) {return false;} return this.book.stores.some(function(store){return store.quantity > 0;})}}return Book;}]) 

以上,通過factory的方式建立了類似Book的一個Data Model,現在可以注入到controller中去了。

app.controller('BookController', ['$scope', 'Book', function($scope, Book){$scope.book = new Book();$scope.book.load(1);}]) 

在視圖中也會有相應的變化。

<div ng-controller="BookController"><div ng-style="{backgroundImage: 'url(' + book.getImageUrl(100, 100) + ')'}"></div><span ng-bind="book.id"></span><input type="text" ng-model="book.name"/><input type="text" ng-model="book.author"/>is abailble: <span ng-bind="book.isAvailabe() ? 'Yes' : 'No'"></span><button ng-click="book.delete()">Delete</button><button ng-click="book.update()">Update</button></div> 

以上,多個controller可以使用同一個有關book的Data Model了,如果多個controller處理同一個有關book的Data Model呢?

app.factory('booksManager', ['$http', '$q', 'Book', function($http. $q, Book){var booksManager = {_pool: {},_retrieveInstance: function(bookId, bookData){var instance = this._pool[bookId];if(instance){instance.setData(bookData);} else {instance = new Book(bookData);this._pool[bookId] = instance;}return instance;},_seach: function(bookId){reutrn this_.pool[bookId];},_load: function(bookId, deferred){var scope = this;$http.get('api/books/' + bookId).success(funciton(bookData){var book = scope._retrieveInstance(bookData.id, bookData);deferred.resolve(book);}).error(function(){deferred.reject();})},getBook: function(bookId){var deferred = $q.defer();var book = this._search(bookId);if(book){deferred.resove(book);} else {this._load(bookId, deferred);}return deferred.promise;},loadAllBooks: function(){var deferred = $q.defer();var scope = this;$http.get('api/books').success(function(booksArray){var books = [];booksArray.forEach(function(bookData){var book = scope.l_retrieveInstance(bookData.id, bookData);books.push(book);});deferred.resolve(books);}).error(function(){deferred.reject();});return deferred.promise;},setBook: function(bookData){var scope = this;var book = this._search(bookData.id);if(book){book.setData(bookData);} else {book = scope._retrieveInstance(bookData);}return book;}};return booksManager;}]) 

Book服務去掉load方法。

app.factory('Book', ['$http', function($http) { function Book(bookData) {if (bookData) {this.setData(bookData):}// Some other initializations related to book};Book.prototype = {setData: function(bookData) {angular.extend(this, bookData);},delete: function() {$http.delete('ourserver/books/' + bookId);},update: function() {$http.put('ourserver/books/' + bookId, this);},getImageUrl: function(width, height) {return 'our/image/service/' + this.book.id + '/width/height';},isAvailable: function() {if (!this.book.stores || this.book.stores.length === 0) {return false;}return this.book.stores.some(function(store) {return store.quantity > 0;});}};return Book;}]); 

現在,多個controller可以使用同一個booksManager服務。

app.controller('EditableBookController',['$scope', 'booksManager', function($scope, booksManager){booksManager.getBook(1).then(function(book){$scope.book = book;})}]).controller('BooksListController',['$scope', 'booksManager', function($scope, booksManager){booksManager.loadAllBooks().then(function(books){$scope.books = books;})}])

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.