Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $11.99/month after trial. Cancel anytime.

50 Recipes for Programming Angular
50 Recipes for Programming Angular
50 Recipes for Programming Angular
Ebook412 pages2 hours

50 Recipes for Programming Angular

Rating: 4 out of 5 stars

4/5

()

Read preview

About this ebook

50 Recipes on Programming Angular is structured in a Cookbook format featuring recipes that contain problem statements with solutions. A detailed explanation follows each problem statement of the recipe. This is usually contained within the solution; however, an optional discussion section can often contain other useful information helping to demonstrate how the solution works or if there are alternative solutions.

Angular.js is a JavaScript-based open-source front-end web application framework mainly maintained by Google and by a community of individuals and corporations to address many of the challenges encountered in developing single-page applications. The JavaScript components complement Apache Cordova, the framework used for developing cross-platform mobile apps. It aims to simplify both the development and the testing of such applications by providing a framework for client-side model–view–controller (MVC) and model–view–viewmodel (MVVM) architectures, along with components commonly used in rich Internet applications.

LanguageEnglish
PublisherJamie Munro
Release dateAug 1, 2017
ISBN9781370370573
50 Recipes for Programming Angular
Author

Jamie Munro

I have been developing websites both personally and professionally for the past 15 years. During this time I’ve helped engineer dozens of small and large projects using CakePHP as the framework. The ideas and methodologies behind this book all stem from my experience with providing quality web applications to my clients. I am well versed in many web technologies as well as several software development languages. My brain is constantly working as I’m always looking to better myself as I strive to continue my role as lead developer. For more information, visit my blog at http://www.endyourif.com

Read more from Jamie Munro

Related to 50 Recipes for Programming Angular

Related ebooks

Programming For You

View More

Related articles

Reviews for 50 Recipes for Programming Angular

Rating: 4 out of 5 stars
4/5

1 rating0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    50 Recipes for Programming Angular - Jamie Munro

    50 Recipes for Programming Angular.js

    Volume 1

    Organized by: Jamie Munro

    This book is dedicated to the user's of StackOverFlow who have asked over 239,000 questions at the time this book was organized.

    Preface

    About the Book

    This book is structured in a Cookbook format featuring recipes that contain problem statements and solutions. A detailed explanation follows each problem statement of the recipe. This is usually contained within the solution; however, an optional discussion section can often contain other useful information helping to demonstrate how the solution works.

    How to contact

    To comment or ask technical questions about this book, send an email to:

    info@angularjsrecipes.com

    For thousands of more recipes, visit our online version of the site at Angular.js Recipes.

    Find us on Facebook: https://www.facebook.com/Angularjs-Recipes-119861211980524/

    Find us on Twitter: https://twitter.com/angular_recipe

    The Recipes

    angular.js example in backbone.js and/or knockout.js

    How to connect couchDB with angular.js?

    How to use angular.scope.$bind

    How to test angular controller with JsTestDriver?

    Drag and drop sortable ng:repeats in Angular.JS?

    Google Angular Framework - Worth the risk?

    What is the best way to conditionally apply a class?

    How can I use AngularJS data binding with CKEditor?

    AngularJS with Django - Conflicting template tags

    Can one controller call another?

    Insert HTML into view

    Angularjs click and display from a list

    How to access couchdb cross domain from angularjs

    How does data binding work in AngularJS?

    Can I use another prefix instead of `ng` with angularjs?

    Passing json object to python using angularjs

    $resource relations in Angular.js

    Convert an Angular function to service

    The view is not updated in AngularJS

    Optional url parameters in AngularJs Resource

    Binding checkboxes to object values in AngularJs

    How would I render a dynamic definition list using angular?

    Cannot get to $rootScope

    Call Angular JS from legacy code

    In AngularJS, how do you find all the scopes on a page?

    AngularJS - $http POST with Rails 3.2.3

    AngularJS - Value attribute on an input text box is ignored when there is a ng-model used?

    Customizing the template within a Directive

    Angularjs : Learning how ngChecked works

    AngularJS how to bind data with SVG widget

    Tracking Google Analytics Page Views with Angular.js

    AngularJS - jQuery UI - binding issue

    Angular ng-style not changing with property

    Remove table row after object destroyed

    Angular: basic testing with injection

    How to do paging in AngularJS?

    Need for value attribute in directive 'scope'

    AngularJS and generated elements

    AngularJS linky filter throws an "Unknown Provider" error

    How to preventDefault on anchor tags?

    AngularJS - How can I reference the property name within an ng-Repeat

    How to access cookies in AngularJS?

    Is there a way to interact with controller and scope directly in Angularjs?

    How can I list by keys and values in angularjs?

    AngularJS : How do I switch views from a controller function?

    html5, angularJS with closure compiler and/or closure library

    $resource relations in Angular.js [updated]

    How would I use AngularJS ng-repeat with Twitter Bootstrap's scaffolding?

    eval on expression of ngrepeat

    Brunch how to disable RequireJS module wrapping

    angular.js example in backbone.js and/or knockout.js

    Problem

    I'm comparing these frameworks to do some calculations on the client side. I really liked the example on the angular.js site. I was wondering if any of the backbone.js or knockout.js experts on the site would please recreate that example in their respective frameworks.

    Here is the JSFiddle for it.

    Code of the Fiddle:

    invoice= {items:[{qty:10, description:'gadget', cost:9.95}]}>

     

        Qty

        Description

        Cost

        Total

       

     

      item in invoice.items>

        item.qty value=1 size=4 ng:required ng:validate=integer>

        item.description>

        item.cost value=0.00 ng:required ng:validate=number size=6>

        {{item.qty * item.cost | currency}}

        [invoice.items.$remove(item)>X]

     

     

        invoice.items.$add()>add item

       

        Total:

        {{invoice.items.$sum('qty*cost') | currency}}

     

      Workaround for jsfiddle to pass in ng:autobind

      http://doc.jsfiddle.net/basic/introduction.html#css

    -->

     

    table th {

      font-weight: bold;

    }

    table td {

      padding: 0.3em;

    }

    Problem courtesy of: aa_memon

    Solution

    Here you go for knockoutjs >

    http://jsfiddle.net/neebz/YbwzJ/

    I might be biased but it's a lot more structural than angular/backbone.

    If you have any questions, let me know.

    There are some NaN checks which I think you could take yourself.

    Solution courtesy of: neebz

    Discussion

    Also have a look https://github.com/addyosmani/todomvc which show a standard TODO app written in all popular frameworks.

    Discussion courtesy of: Misko Hevery

    This content originated from StackOverFlow and has been re-organized into the above recipe.

    How to connect couchDB with angular.js?

    Problem

    I have searched for this but did not get proper answer if we can connect couchDB directly with angular.js framework

    or

    We have to take help of node.js for that.

    Problem courtesy of: Ashvin

    Solution

    While I have no experience of angular.js, looking at the Google Buzz example it appears to have a way to deal with JSON-providing resources. Since this is exactly what CouchDB is, I don't think there is any need for node.js to be involved.

    All CouchDB functionality can be accessed via HTTP requests, so it should fit right in, if necessary by doing AJAX calls. The angular.service.$resource looks to be the appropriate candidate.

    Solution courtesy of: Colin Ross

    Discussion

    Ashvin, thanks for asking this. I too struggle with this issue.

    I have not yet figured out how to use $resource to call the local CouchDB from AngularJS, since it uses a full localhost URL like this:

    http://localhost:5984//_all_docs

    and all of the AngularJS docs and examples show local pathnames. They don't really tell one how to reach out to a separate web service, or at least I haven't found an explanation that helps :)

    Here's a way to use jQuery that was easier for me to understand. I placed this in a file named couch.js - to connect to a CouchDB of our critters (dogs, cats, etc). The actual module (app) is defined elsewhere in the app, so I just put it in a variable named app and added a Couch controller like so:

    (function () {

        'use strict';

        var app = angular.module('app');

        app.controller('CouchCtrl', function ($scope,$http,$resource) {

            var all_critters = 'http://localhost:5984/critters/_all_docs?callback=?';

            $.getJSON(all_critters, function(json) {

                $scope.$apply(function(){

                    $scope.all_critters = json;

                });

            });

            $scope.getAllCritters = function() {

                return $scope.all_critters;

            };

        });

    }());

    I added the ?callback=? for JSONP to avoid localhost security issues with the browsers while I worked locally, so I set JSONP = true in the CouchDB preferences.

    In an html page, just look at the result of this call by putting crittersDB in a binding:

      CouchCtrl>

       

    Critters

       

    There are currently {{all_critters.total_rows}} critters.

       

  • (key,value) in all_critters>
  •         {{key}} - {{value}}

       

    If anyone could post some actual AngularJS $resource code to replicate this jQUery.getJSON way of pulling data from CouchDB into an AngularJS app, I'd appreciate it.

    Discussion courtesy of: noogrub

    The trick is that your page that includes queries to the couchdb must be served from the same address and port as couchdb itself. This can be accomplished by serving your html by couchdb, or by installing a proxy that would act as umbrella for both your web server hosting the html and couchdb.

    Discussion courtesy of: Davorin Ruševljan

    I've created an AngularJS module called CornerCouch that improves on the approach of the AngularJS $resource by tailoring it specifically for CouchDB. It is based on the $http service in AngularJS. I ended up with nice clean JavaScript code that way, especially in the app specific AngularJS controller.

    CornerCouch AngularJS Module

    Making the calls directly leaves three options, as far as I know:

    Load the html app directly from a CouchDB attachement (CouchApp approach)

    Use a transparent proxy as included in the Jetty project (Java app stack)

    Access via GET only, but using JSONP, after enabling it on the CouchDB server

    Everything else does not get by cross-site scripting restrictions.

    Discussion courtesy of: eddelplus

    I've modified the example on the AngularJS website to use CouchDB instead of mongolab. See the jsfiddle here http://jsfiddle.net/WarwickGrigg/dCCQF/ and github repository here https://github.com/telanova/angularjs-couchdb. I'm an angular newbie: I found it a struggle to get my head round $resource, but it seems to work well.

    $scope.projects = ProjectCouch.get({q:'_all_docs', include_docs: 'true', limit: 10});

     

    angular.module('CouchDB', ['ngResource']).

        factory('ProjectCouch', function($resource) {

            var ProjectCouch = $resource(':protocol//:server/:db/:q/:r/:s/:t',

                                        {protocol: 'http:', server: 'localhost:5984', db:'projects'}, {update: {method:'PUT'} 

                              }

      );

     

      ProjectCouch.prototype.update = function(cb) {

        return ProjectCouch.update({q: this._id},

            this, cb);

      };

     

      ProjectCouch.prototype.destroy = function(cb) {

          return ProjectCouch.remove({q: this._id, rev: this._rev}, cb);

      };

     

      return ProjectCouch;

    });

    Discussion courtesy of: Warwick

    This content originated from StackOverFlow and has been re-organized into the above recipe.

    How to use angular.scope.$bind

    Problem

    I have the following controller which works fine:

    function Controller() {}

     

    Controller.prototype = {

        getResult: function(project) {

            var that = this;

     

            jQuery.ajax({

                async: false,

                url: /my-service/call?project= + project,

                dataType: json,

                success: function(data) {

                    that.result = data;

                }

            });

        }

    };

    I'd like to use angular.scope.$bind to see if I could eliminate the 'var that = this;' hack. But the following doesn't work:

    function Controller() {}

     

    Controller.prototype = {

        getResult: function(project) {

            angular.scope.$bind(jQuery.ajax({

                async: false,

                url: /my-service/call?project= + project,

                dataType: json,

                success: function(data) {

                    this.result = data;

                }

            }))();

        }

    };

    What am I missing?

    Problem courtesy of: Noel Yap

    Solution

    Misko Hevery on the angular mailing responded with:

    Controller.prototype = {

        getStuff: function(project) {

            jQuery.ajax({

                        async: false,

                        url: /service/get-stuff,

                        dataType: json,

                        success: angular.bind(this, function(data) {

                            this.stuff = data;

                        })

                    });

        }

    };

    He also suggested using angular.service.$xhr instead of jQuery.ajax.

    Solution courtesy of: Noel Yap

    Discussion

    There is currently no discussion for this recipe.

    This content originated from StackOverFlow and has been re-organized into the above recipe.

    How to test angular controller with JsTestDriver?

    Problem

    I have the following code:

    function TestStats($xhr) {

        $xhr(

                'GET',

                '/test-dashboard/get-projects.json',

                angular.bind(this, function(code, response) {

                    this.projects = response.projects;

                    this.projects.splice(0, 0, undefined);

                }));

     

        this.$watch('project', angular.bind(this, function() {

            this.testClassStats = undefined;

     

            if (this.project) {

                $xhr(

                        'GET',

                        '/test-dashboard/get-test-stats.json?project=' + this.project,

                        angular.bind(this, function(code, response) {

                            this.testClassStats = response.testClassStats;

                        }));

            }

        }));

    };

     

    TestStats.prototype.greet = function(name) {

      return Hello + name + !;

    };

     

    TestStats.$inject = ['$xhr'];

    and the following test:

    TestDashboardUnitTest = TestCase(TestDashboardUnitTest);

     

    TestDashboardUnitTest.prototype.testAoeu = function() {

        var xhrStub = function(method, url, callback) {

        };

        var testStats = new TestStats(xhrStub);

        assertEquals(Hello World!, testStats.greet(Aoeu));

    };

    and the following config:

    server: http://localhost:9876

     

    load:

      - http://code.jquery.com/jquery-1.6.2.min.js

      - http://code.angularjs.org/angular-0.9.17.min.js

      - web/*.js

      - test/*.js

    When I run the test, JsTestDriver outputs:

    Total 1 tests (Passed: 0; Fails: 0; Errors: 1) (0.00 ms)

      Chrome 13.0.782.112 Linux: Run 1 tests (Passed: 0; Fails: 0; Errors 1) (0.00 ms)

        TestDashboardUnitTest.testAoeu error (0.00 ms): TypeError: Object # has no method '$watch'

          TypeError: Object # has no method '$watch'

              at new TestStats (http://127.0.0.1:9876/test/web/test-dashboard.js:13:10)

              at [object Object].testAoeu (http://127.0.0.1:9876/test/test/test-dashboard-unit-test.js:9:21)

     

    Tests failed: Tests failed. See log for details.

    What do I need to do to fix this?

    Problem courtesy of: Noel Yap

    Solution

    From http://docs.angularjs.org/#!/tutorial/step_05

    scope =

    Enjoying the preview?
    Page 1 of 1