[Angular-Scaled Web] Refactor code into Models

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.

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>
时间: 2024-07-28 13:47:13

[Angular-Scaled Web] Refactor code into Models的相关文章

angular和web前端的一些细节

HTML5中的本地存储localStorage:一直存储在本地sessionStorage:伴随着session,窗口关闭就没了用法:localStorage.setItem("key","value")//设置变量localStorage.getItem("key")//获取变量localStorage.removeItem("key")//清除变量 angularJS中scope和rootscope的区别scope:用于单

[Angular 2] Better ES5 Code

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>JS Bin</title> <script src="https://code.angularjs.org/2.0.0-alpha.28/angular2.sfx.dev.js"></script> <link rel="stylesh

25+ Useful Selenium Web driver Code Snippets For GUI Testing Automation

本文总结了使用Selenium Web driver 做页面自动化测试的一些 tips, tricks, snippets. 1. Chrome Driver 如何安装 extensions 两种方式 a) Packed (.crx file) --  crx为Chrome的插件后缀名,FireFox的是xpi ChromeOptions options = new ChromeOptions(); options.addExtensions(new File("/path/to/extensi

ASP.NET Web API实践系列02,在MVC4下的一个实例, 包含EF Code First,依赖注入, Bootstrap等

本篇体验在MVC4下,实现一个对Book信息的管理,包括增删查等,用到了EF Code First, 使用Unity进行依赖注入,前端使用Bootstrap美化.先上最终效果: →创建一个MVC4项目,选择Web API模版. →在Models文件夹创建一个Book.cs类. namespace MyMvcAndWebApi.Models { public class Book { public int Id { get; set; } public string Name { get; set

angular custom Element 自定义web component

angular 自定义web组件: 首先创建一个名为myCustom的组件. 引入app.module: ... import {customComponent} from ' ./myCustom.component'; @NgModule({ declarations:[AppComponent,customComponent], entryComponents:[customComponent] .... }) export class AppModule{} 全局注册: app.comp

从angularjs传递参数至Web API

昨天分享的博文<angularjs呼叫Web API>http://www.cnblogs.com/insus/p/7772022.html,只是从Entity获取数据,没有进行参数POST. 今天分享一个例子,是传递参数至Web API来获取数据的.而且数据是存储在SQL中.数表结构是昨晚帮助网友解解决问题列举的: CREATE TABLE [dbo].[TA] ( [Aid] NVARCHAR(20), [Avalue] NVARCHAR(30) ) GO INSERT INTO [dbo

.NET跨平台之mac 下vs code 多层架构编程

合肥程序员群:49313181.    合肥实名程序员群:128131462 (不愿透露姓名和信息者勿加入,申请备注填写姓名+技术+工作年限) Q  Q:408365330     E-Mail:[email protected] 概述: 为了研究跨平台.NET 开发,我打算利用.NET core 编写一个跨平台的cms,这个CMS我也秉着开源的原则放到github上面,为.NET 开源社区做点小小的贡献吧.如果有兴趣的可以联系我一起为.NET开源和跨平台做点小小的贡献吧.EgojitCMS传送

python开发学习-day15(前端部分知识、web框架、Django创建项目)

s12-20160430-day15 *:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: 0 !important; } /* BLOCKS =============================================================================*/ p, blockquote, ul, ol, dl, table, pre { margin

【ASP.NET Web API教程】2.4 创建Web API的帮助页面

参考页面: http://www.yuanjiaocheng.net/CSharp/csharprumenshili.html http://www.yuanjiaocheng.net/entity/mode-first.html http://www.yuanjiaocheng.net/entity/database-first.html http://www.yuanjiaocheng.net/entity/choose-development-approach.html http://ww