Showing posts with label AngularJS. Show all posts
Showing posts with label AngularJS. Show all posts

Saturday, September 19, 2015

External Javascript Resources in Ionic Applications

Fun Fact: If you're using an externally referenced Javascript file in your Ionic browser, it will 404 out due to the default content policy on Android phones. This happened to me recently while I was working on an app that uses the Google Maps API to geocode locations.

Running the app in your browser via `ionic serve` does not reflect the issue - it appears only on actual devices. When I built the app and installed it on my phone, it showed me a very helpful blank screen.

I connected the Chrome debugger to the Ionic webview on my phone, and pretty soon tracked the problem down to the Google Maps API js file erroring out. A quick Google search revealed that the best way to get around this issue is to run `cordova plugin add cordova-plugin-whitelist`. The Whitelist plugin allows you to load third party Javascript files as part of your Ionic app. I'm surprised this isn't officially documented anywhere in the Ionic documentation - it seems like a pretty crucial issue to me!

Sunday, November 16, 2014

Learning Angular | Using a factory to make an API call

I was recently building an Angular app in which I had a search page and a search results page. Obviously, the API call would be made after a user hit the search button on the search page, but the question was whether I should make the call from the search page or the search results page.

Search page on the left, search results on the right
My initial solution was extremely complex - I tried recording the selected parameters, and then I created a super-complicated route that allowed me to pass them into the the search results page. However, that was way too complicated, and I quickly realized that there had to be a better way.

After asking around a bit on some Angular help channels, I figured out that Angular services and factories are singletons! This means that I can make the call in the search controller, store the results in my API factory, and then bootstrap my search results controller user the cached results. This ended up being a much faster, simpler, neater implementation!

Here's how my final implementation worked:

Search function - searchController.js

$scope.search = function() {
        var searchParameters = {
            // create search object
        }
        
        API.search(searchParameters).success(function (data, status, headers, config) {
            $location.url('/results');
        });
    };


Controller - searchResultsController.js

// gets the cached results from the API
var data = API.getSearchResults();

    

API factory - API.js

angular.module("donorsApp").factory("API", ["$http", function ($http) {
    
    var constructSearchUrl = function (searchParameters) {
        //returns URL;
    }
    
    // cached results
    var results = null;
    
    return {

        // gets called from the searchController             
        search : function (searchParameters) {
            var request = $http.jsonp(constructSearchUrl(searchParameters));
            
            request.success(function (data, status, headers, config) {
                // caches the returned results
                results = data;
            });
            
            return request;
        },
        
        // gets called from the searchResultsController
        getSearchResults: function() {
            return results;
        }
        
    }
    

}]);

Lesson learned: don't make API calls from the controller, make them from a factory or a service, and then cache the results as needed. 

Sunday, September 21, 2014

Discovering AngularJS

I've recently been pointed towards AngularJS by a mentor. At work, we typically use BackboneJS for our client-side framework needs. Since Backbone is so minimalist, over the past few years we've learned some (sometimes expensive) lessons and developed a set of best practices that minimize the pain of developing with Backbone.

The first thing I noticed when looking at Angular was how many of those implicit lessons and best practices become unnecessary! For example, it's not unusual for me to have to reimplement two-way binding for every application, and I've seen some complex mechanisms to do as-you-type filtering of a list. With Angular, it's so incredibly easy!

For example:

    <body>
        <div class="container" data-ng-controller="SomeController">
           
            <h3>Controllers</h3>
            Name: <input type="text" data-ng-model="nameFilter" />
            <ul>
                <li data-ng-repeat="person in people | filter:nameFilter">
                    {{person.name | uppercase}} loves {{person.city | uppercase}}
                </li>

            </ul>
        </div>
       
        <script type="text/javascript" src="js/libs/angular.min.js"></script>
        <script type="text/javascript" src="js/viewcontrollerscope.js"></script>
    </body>


And in the JS:

var demoApp = angular.module("demoApp", []);

var controllers = {};

controllers.SomeController =  function ($scope) {
    $scope.people = [
        { name: "Kim", city: "Green Bay" },
        { name: "Ron", city: "Miami" },
        { name: "Rufus", city: "Houston" },
        { name: "Wade", city: "San Francisco" }
    ];
};

demoApp.controller(controllers);



Boom! That's it. Most of that code is just boilerplate required to setup Angular itself, and one you do that, the filtering mechanism is handled within the bolded part of HTML template. Isn't that incredible?

I think I'm a little biased against Backbone because it was my first JS framework, and so the learning curve was obviously higher. However, I have to acknowledge, that Backbone is incredibly useful for adding small, clientside-driven pieces to an application. As far as I can tell, Angular seems much better oriented towards writing applications that are entirely clientside, single-page applications.

I highly recommend this tutorial for learning Angular. I found it incredibly useful. Let me know if you have any recommendations for Angular-related resources!