码迷,mamicode.com
首页 > Web开发 > 详细

[Angular-Scaled Web] Refactor code into Models

时间:2014-12-11 18:58:22      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   io   ar   color   os   sp   

In the previous code, both categories and bookmarks are binded to $rootscope, or let says the same scope.

 

eggly-app.js:

angular.module(‘Eggly‘, [
    ‘ui.router‘,
    ‘categories‘,
    ‘categories.bookmarks‘
])
    .config(function($stateProvider, $urlRouterProvider){
        $stateProvider
            .state(‘eggly‘, {
                url:‘‘,
                abstract: true
                //abstract: To prepend a url to all child state urls.
            });

        $urlRouterProvider.otherwise(‘/‘);
    })

    .controller(‘MainController‘, function ($scope , $state) {
        $scope.categories = [
            {"id": 0, "name": "Development"},
            {"id": 1, "name": "Design"},
            {"id": 2, "name": "Exercise"},
            {"id": 3, "name": "Humor"}
        ];

        $scope.bookmarks = [
            {"id": 0, "title": "AngularJS", "url": "http://angularjs.org", "category": "Development" },
            {"id": 1, "title": "Egghead.io", "url": "http://angularjs.org", "category": "Development" },
            {"id": 2, "title": "A List Apart", "url": "http://alistapart.com/", "category": "Design" },
            {"id": 3, "title": "One Page Love", "url": "http://onepagelove.com/", "category": "Design" },
            {"id": 4, "title": "MobilityW OD", "url": "http://www.mobilitywod.com/", "category": "Exercise" },
            {"id": 5, "title": "Robb Wolf", "url": "http://robbwolf.com/", "category": "Exercise" },
            {"id": 6, "title": "Senor Gif", "url": "http://memebase.cheezburger.com/senorgif", "category": "Humor" },
            {"id": 7, "title": "Wimp", "url": "http://wimp.com", "category": "Humor" },
            {"id": 8, "title": "Dump", "url": "http://dump.com", "category": "Humor" }
        ];

        $scope.isCreating = false;
        $scope.isEditing = false;
        $scope.currentCategory = null;
        $scope.editedBookmark = null;

    ...
...
... })

 

It is not good to put those json array into the main script file. We have the file structure, which all the models are consided as common part.

It likes MVC‘s model. 

bubuko.com,布布扣

 

1. So cut the data part into a spreate json file.

2. Using $http ‘Service‘ to fetch the data.

3. Encapsulate into angular service.

 

bookmarks.json:

[
    {"id":0, "title": "AngularJS", "url": "http://angularjs.org", "category": "Development" },
    {"id":1, "title": "Egghead.io", "url": "http://angularjs.org", "category": "Development" },
    {"id":2, "title": "A List Apart", "url": "http://alistapart.com/", "category": "Design" },
    {"id":3, "title": "One Page Love", "url": "http://onepagelove.com/", "category": "Design" },
    {"id":4, "title": "MobilityWOD", "url": "http://www.mobilitywod.com/", "category": "Exercise" },
    {"id":5, "title": "Robb Wolf", "url": "http://robbwolf.com/", "category": "Exercise" },
    {"id":6, "title": "Senor Gif", "url": "http://memebase.cheezburger.com/senorgif", "category": "Humor" },
    {"id":7, "title": "Wimp", "url": "http://wimp.com", "category": "Humor" },
    {"id":8, "title": "Dump", "url": "http://dump.com", "category": "Humor" }
]

categories.json:

[
    {"id": 0, "name": "Development"},
    {"id": 1, "name": "Design"},
    {"id": 2, "name": "Exercise"},
    {"id": 3, "name": "Humor"}
]

 

Bookmarks-model.js:

angular.module(‘eggly.models.bookmarks‘, [

])
    .service(‘BookmarksModel‘, function($http){
        var BookmarksModel = {},
            URLS = {
                FETCH: ‘data/bookmarks.json‘
            },
            bookmarks;

        function extract(result) {
            return result.data;
        }

        function cacheBookmarks(result) {
            bookmarks = extract(result);
            return bookmarks;
        }

        BookmarksModel.getBookmarks = function() {
            return $http.get(URLS.FETCH).then(cacheBookmarks);
        };

        return BookmarksModel;
    })

;

 

categories-model.js:

angular.module(‘eggly.models.categories‘, [

])
    .service(‘CategoriesModel‘, function ($http, $q) {
        var model = this,
            URLS = {
                FETCH: ‘data/categories.json‘
            },
            categories;

        function extract(result) {
            return result.data;
        }

        function cacheCategories(result) {
            categories = extract(result);
            return categories;
        }

        model.getCategories = function() {
            return (categories) ? $q.when(categories) : $http.get(URLS.FETCH).then(cacheCategories);
        };

        model.getCategoryByName = function(categoryName) {
            var deferred = $q.defer();

            function findCategory(){
                return _.find(categories, function(c){
                    return c.name == categoryName;
                })
            }

            if(categories) {
                deferred.resolve(findCategory());
            } else {
                model.getCategories()
                    .then(function() {
                        deferred.resolve(findCategory());
                    });
            }

            return deferred.promise;
        };


    })
;

 

categories.tmpl.html:

<a ng-click="setCurrentCategory(null)"><img class="logo" src="assets/img/eggly-logo.png"></a>
<ul class="nav nav-sidebar">
    <li ng-repeat="category in categoriesListCtrl.categories" ng-class="{‘active‘:isCurrentCategory(category)}">
        <a ui-sref="eggly.categories.bookmarks({category:category.name})">
            {{category.name}}
        </a>
    </li>
</ul>

 

bookmarks.tmpl.html:

<h1>{{bookmarksListCtrl.currentCategoryName}}</h1>
<div ng-class="{active: isSelectedBookmark(bookmark.id)}"  ng-repeat="bookmark in bookmarksListCtrl.bookmarks | filter:{category:currentCategory.name}">
    <button type="button" class="close" ng-click="deleteBookmark(bookmark)">&times;</button>
    <button type="button" class="btn btn-link" ng-click="setEditedBookmark(bookmark);startEditing();" ><span class="glyphicon glyphicon-pencil"></span>
    </button>
    <a href="{{bookmark.url}}" target="_blank">{{bookmark.title}}</a>
</div>
<hr/>
<!-- CREATING -->
<div ng-if="shouldShowCreating()">
    <button type="button" class="btn btn-link" ng-click="startCreating()">
        <span class="glyphicon glyphicon-plus"></span>
        Create Bookmark
    </button>
    <form class="create-form" ng-show="isCreating" role="form" ng-submit="createBookmark(newBookmark)" novalidate>
        <div class="form-group">
            <label for="newBookmarkTitle">Bookmark Title</label>
            <input type="text" class="form-control" id="newBookmarkTitle" ng-model="newBookmark.title" placeholder="Enter title">
        </div>
        <div class="form-group">
            <label for="newBookmarkURL">Bookmark URL</label>
            <input type="text" class="form-control" id="newBookmarkURL" ng-model="newBookmark.url" placeholder="Enter URL">
        </div>
        <button type="submit" class="btn btn-info btn-lg">Create</button>
        <button type="button" class="btn btn-default btn-lg pull-right" ng-click="cancelCreating()">Cancel</button>
    </form>
</div>
<!-- EDITING -->
<div ng-show="shouldShowEditing()">
    <h4>Editing {{editedBookmark.title}}</h4>

    <form class="edit-form" role="form" ng-submit="updateBookmark(editedBookmark)" novalidate>
        <div class="form-group">
            <label>Bookmark Title</label>
            <input type="text" class="form-control" ng-model="editedBookmark.title" placeholder="Enter title">
        </div>
        <div class="form-group">
            <label>Bookmark URL</label>
            <input type="text" class="form-control" ng-model="editedBookmark.url" placeholder="Enter URL">
        </div>
        <button type="submit" class="btn btn-info btn-lg">Save</button>
        <button type="button" class="btn btn-default btn-lg pull-right" ng-click="cancelEditing()">Cancel</button>
    </form>
</div>

 

[Angular-Scaled Web] Refactor code into Models

标签:des   style   blog   http   io   ar   color   os   sp   

原文地址:http://www.cnblogs.com/Answer1215/p/4158148.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!