<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:a10="http://www.w3.org/2005/Atom" version="2.0"><channel><title>OdeToCode by K. Scott Allen</title><description>OdeToCode by K. Scott Allen</description><copyright>(c) 2004 to 2013 OdeToCode LLC</copyright><managingEditor>scott@OdeToCode.com</managingEditor><generator>OdeToCode 2.0 with ASP.NET MVC 4</generator><image><url>http://odetocode.com/images/odetocode.jpg</url><title>OdeToCode by K. Scott Allen</title><link /></image><a10:link href="http://odetocode.com/" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/OdeToCode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="odetocode" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item><guid isPermaLink="true">http://odetocode.com/blogs/scott/archive/2013/06/19/using-ngoptions-in-angularjs.aspx</guid><link>http://odetocode.com/blogs/scott/archive/2013/06/19/using-ngoptions-in-angularjs.aspx</link><author>scott@OdeTocode.com</author><title>Using ngOptions In AngularJS</title><description>&lt;p&gt;&lt;img style="float: right; margin: 0px 0px 5px 5px; display: inline" align="right" src="http://odetocode.com/images2/Windows-Live-Writer/Angular-Abstractions-The-Application_F661/image_3.png"&gt;The ngOptions directive in AngularJS allows you to build and bind an HTML select element with options to a model property. It’s quite a versatile directive and is smarter than trying to build the select options with ngRepeat since ngOptions is optimized for two way data binding. &lt;/p&gt; &lt;p&gt;There are some tricks, however. &lt;/p&gt; &lt;p&gt;Let’s start with the following simple controller in JavaScript. &lt;/p&gt;&lt;pre class="brush: js; gutter: false; toolbar: false;"&gt;var EngineeringController = function($scope) {

    $scope.engineer = {
        name: "Dani",
        currentActivity: "Fixing bugs"
    };

    $scope.activities =
    [
        "Writing code",
        "Testing code",
        "Fixing bugs",
        "Dancing"
    ];        
};
&lt;/pre&gt;
&lt;p&gt;The goal is to build a drop down list to select an engineer’s current activity. &lt;/p&gt;&lt;pre class="brush: xml; gutter: false; toolbar: false;"&gt;&amp;lt;div data-ng-controller="EngineeringController"&amp;gt;
    {{engineer.name}} is currently: {{ engineer.currentActivity}}
    &amp;lt;div&amp;gt;
        Choose a new activity:
        &amp;lt;select data-ng-model="engineer.currentActivity" 
                data-ng-options="act for act in activities"&amp;gt;                
        &amp;lt;/select&amp;gt;
    &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/pre&gt;
&lt;p&gt;One of the tricks to using ngOptions is figuring out the expression AngularJS expects. The current value of “&lt;em&gt;act for act in activities&lt;/em&gt;” is telling AngularJS to use the value of each entry in the &lt;em&gt;activities&lt;/em&gt; array. This syntax against a simple array of strings allows the select element to appear with the engineer’s current activity selected, and if the selected option changes the framework updates the engineer’s current activity (and vice versa). &lt;/p&gt;
&lt;p&gt;&lt;a href="http://odetocode.com/images2/Windows-Live-Writer/22386abad5c1_C05B/image_2.png"&gt;&lt;img title="image" style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; padding-top: 0px; padding-left: 0px; border-left: 0px; display: inline; padding-right: 0px" border="0" alt="image" src="http://odetocode.com/images2/Windows-Live-Writer/22386abad5c1_C05B/image_thumb.png" width="402" height="75"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;The expression you can use with ngOptions can be quite a bit more advanced (which could be good or bad). For example, instead of using strings let’s use objects to represent an activity. &lt;/p&gt;&lt;pre class="brush: js; gutter: false; toolbar: false;"&gt;var EngineeringController = function($scope) {

    $scope.engineer = {
        name: "Dani",
        currentActivity: {
            id: 3,
            type: "Work",
            name: "Fixing bugs"
        }
    };

    $scope.activities =
    [
        { id: 1, type: "Work", name: "Writing code" },
        { id: 2, type: "Work", name: "Testing code" },
        { id: 3, type: "Work", name: "Fixing bugs" },
        { id: 4, type: "Play", name: "Dancing" }
    ];        
};
&lt;/pre&gt;
&lt;p&gt;And we’ll change the ngOptions expression to build a label for the select option. &lt;/p&gt;&lt;pre class="brush: xml; gutter: false; toolbar: false;"&gt;&amp;lt;select data-ng-model="engineer.currentActivity" 
        data-ng-options="a.name +' (' + a.type + ')' for a in activities"&amp;gt;                
&amp;lt;/select&amp;gt;
&lt;/pre&gt;

&lt;p&gt;This produces:&lt;/p&gt;
&lt;p&gt;&lt;a href="http://odetocode.com/images2/Windows-Live-Writer/22386abad5c1_C05B/image_4.png"&gt;&lt;img title="image" style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; padding-top: 0px; padding-left: 0px; border-left: 0px; display: inline; padding-right: 0px" border="0" alt="image" src="http://odetocode.com/images2/Windows-Live-Writer/22386abad5c1_C05B/image_thumb_1.png" width="412" height="151"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Expressions can also create &lt;em&gt;optgroup&lt;/em&gt; elements when using a &lt;em&gt;group by&lt;/em&gt; in the expression. &lt;/p&gt;&lt;pre class="brush: xml; gutter: false; toolbar: false;"&gt;&amp;lt;select ng-model="engineer.currentActivity" 
        data-ng-options="a.name group by a.type for a in activities"&amp;gt;                
&amp;lt;/select&amp;gt;
&lt;/pre&gt;
&lt;p&gt;Which yields:&lt;/p&gt;
&lt;p&gt;&lt;a href="http://odetocode.com/images2/Windows-Live-Writer/22386abad5c1_C05B/image_6.png"&gt;&lt;img title="image" style="border-top: 0px; border-right: 0px; background-image: none; border-bottom: 0px; padding-top: 0px; padding-left: 0px; border-left: 0px; display: inline; padding-right: 0px" border="0" alt="image" src="http://odetocode.com/images2/Windows-Live-Writer/22386abad5c1_C05B/image_thumb_2.png" width="413" height="198"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;What About The Initial Selection?&lt;/h3&gt;
&lt;p&gt;When we switched from an array of strings to activities as objects, we lost the ability for the select to show the starting currentActivity as initially selected. If the user selects a new activity the two-way data binding works and the currentActivity is set, but we lost the initial selection. This is because AngularJS is doing reference comparisons and &lt;em&gt;employee.currentActivity&lt;/em&gt; might by “Fixing bugs”, but &lt;em&gt;employee.currentActivity != activities[2]&lt;/em&gt;, so the page starts with an empty selection in the drop down list. &lt;/p&gt;
&lt;p&gt;This is a common occurrence since the engineer object and the activities list are most likely de-serialized from HTTP calls and will completely different object graphs.&amp;nbsp; There is no good solution with the exiting ngOptions directive but to “fix up” the engineer once the engineer and all the possible activities are loaded. Something like the following (which could be shortened with a library like undercore.js). &lt;/p&gt;&lt;pre class="brush: js; gutter: false; toolbar: false;"&gt;for (var i = 0; i &amp;lt; $scope.activities.length; i++) {
    if ($scope.activities[i].id == $scope.engineer.currentActivity.id) {
        $scope.engineer.currentActivity = $scope.activities[i];
        break;
    }
}
&lt;/pre&gt;
&lt;h3&gt;One Last Variation&lt;/h3&gt;
&lt;p&gt;What if you had objects representing activities but only wanted the Id property of the selected activity instead of the entire activity. The ngOptions expression can handle this scenario, too. Inside the controller would look like this:&lt;/p&gt;&lt;pre class="brush: js; gutter: false; toolbar: false;"&gt;$scope.engineer = {
    name: "Dani",
    currentActivityId: 3
};

$scope.activities =
[
    { id: 1, type: "Work", name: "Writing code" },
    { id: 2, type: "Work", name: "Testing code" },
    { id: 3, type: "Work", name: "Fixing bugs" },
    { id: 4, type: "Play", name: "Dancing" }
];
&lt;/pre&gt;
&lt;p&gt;And the expression would use a &lt;em&gt;select as value&lt;/em&gt; syntax.&lt;/p&gt;&lt;pre class="brush: xml; gutter: false; toolbar: false;"&gt;&amp;lt;select ng-model="engineer.currentActivityId" 
        data-ng-options="a.id as a.name group by a.type for a in activities"&amp;gt;                
&amp;lt;/select&amp;gt;
&lt;/pre&gt;
&lt;p&gt;And that concludes this post on ngOptions. I hope you found the topic stimulating, and stayed on the edge of your seat until these final words. &lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/OdeToCode?a=X3-9gDhKki4:JrskQU3B2Uo:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/OdeToCode?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;</description><pubDate>Wed, 19 Jun 2013 09:12:00 Z</pubDate></item><item><guid isPermaLink="true">http://odetocode.com/blogs/scott/archive/2013/06/18/a-simple-case-for-c-generic-constraints.aspx</guid><link>http://odetocode.com/blogs/scott/archive/2013/06/18/a-simple-case-for-c-generic-constraints.aspx</link><author>scott@OdeTocode.com</author><title>A Simple Case For C# Generic Constraints</title><description>&lt;p&gt;Imagine you need to support multiple projects that retrieve &amp;ldquo;widgets&amp;rdquo; of different types from various data sources. You might start with some simple type definitions that build a core API around widgets and widget storage.&lt;/p&gt;
&lt;pre class="brush: csharp; gutter: false; toolbar: false;"&gt;public class Widget
{
    public int Key { get; set; }        
}

public interface IWidgetStore
{
    Widget GetWidget(int key);
}
&lt;/pre&gt;
&lt;p&gt;The &lt;em&gt;IWidgetStore&lt;/em&gt; interface is needed so that reusable algorithms can work with widgets.&lt;/p&gt;
&lt;p&gt;Given these definitions, someone can build a widget specific for their project.&lt;/p&gt;
&lt;pre class="brush: csharp; gutter: false; toolbar: false;"&gt;public class NamedWidget  : Widget
{        
    public string Name { get; set; }
}
&lt;/pre&gt;
&lt;p&gt;As well as a concrete class for storing widgets.&lt;/p&gt;
&lt;pre class="brush: csharp; gutter: false; toolbar: false;"&gt;public class WidgetStore : IWidgetStore
{
    public Widget GetWidget(int key)
    {          
        return _store.Single(u =&amp;gt; u.Key == key);
    }
    
    readonly List&amp;lt;NamedWidget&amp;gt; _store = new List&amp;lt;NamedWidget&amp;gt;();
}
&lt;/pre&gt;
&lt;p&gt;But the friction in development will start because specific projects don&amp;rsquo;t want to work with &lt;em&gt;Widget&lt;/em&gt;, they want to work with &lt;em&gt;NamedWidget &lt;/em&gt;where business properties like &lt;em&gt;Name&lt;/em&gt; are defined. If every &lt;em&gt;IWidgetStore &lt;/em&gt;can only return &lt;em&gt;Widget&lt;/em&gt;, every caller has to cast the return value of &lt;em&gt;GetWidget &lt;/em&gt;to a type like &lt;em&gt;NamedWidget&lt;/em&gt;.&lt;/p&gt;
&lt;pre class="brush: csharp; gutter: false; toolbar: false;"&gt;var widget = (NamedWidget)store.GetWidget(id);
var name = widget.Name;
&lt;/pre&gt;
&lt;p&gt;One solution is to use an explicit interface definition to hide the IWidgetStore from application developers.&lt;/p&gt;
&lt;pre class="brush: csharp; gutter: false; toolbar: false;"&gt;public class WidgetStore : IWidgetStore
{
    public NamedWidget GetWidget(int key)
    {            
        return _store.Single(u =&amp;gt; u.Key == key);
    }

    Widget IWidgetStore.GetWidget(int key)
    {
        return GetWidget(key);
    }

    readonly List&amp;lt;NamedWidget&amp;gt; _store = new List&amp;lt;NamedWidget&amp;gt;();
}
&lt;/pre&gt;
&lt;p&gt;Now the application code can work with &lt;em&gt;NamedWidget&lt;/em&gt; and still pass the &lt;em&gt;WidgetStore&lt;/em&gt; to other low level algorithms which will access the object through the &lt;em&gt;IWidgetStore&lt;/em&gt; interface.&lt;/p&gt;
&lt;p&gt;But, if the application is trying to stay flexible or testable it might want to continue working with widget stores through the &lt;em&gt;IWidgetStore&lt;/em&gt; interface too, just like the reusable algorithms, and then the code would still need to cast the return value of &lt;em&gt;GetWidget&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;Another solution is to use a generic type parameter to parameterize a widget store with the desired type of widget.&lt;/p&gt;
&lt;pre class="brush: csharp; gutter: false; toolbar: false;"&gt;public interface IWidgetStore&amp;lt;TWidget&amp;gt;
{
    TWidget GetWidget(int key);
}
&lt;/pre&gt;
&lt;p&gt;Now a concrete widget store can implement the interface and return derived &lt;em&gt;Widget&lt;/em&gt; objects.&lt;/p&gt;
&lt;pre class="brush: csharp; gutter: false; toolbar: false;"&gt;public class WidgetStore&amp;lt;TWidget&amp;gt; : 
    IWidgetStore&amp;lt;TWidget&amp;gt;
    where TWidget: Widget
{
    public TWidget GetWidget(int key)
    {
        return _store.Single(u =&amp;gt; u.Key == key);
    }

    readonly List&amp;lt;TWidget&amp;gt; _store = new List&amp;lt;TWidget&amp;gt;();
}
&lt;/pre&gt;
&lt;p&gt;What makes it all work is the generic constraint &lt;em&gt;where TWidget: Widget&lt;/em&gt;. The C# complier assumes a &lt;em&gt;TWidget&lt;/em&gt; is of type &lt;em&gt;Object&lt;/em&gt; unless told otherwise, so the LINQ query in &lt;em&gt;GetWidget&lt;/em&gt; will fail with a compiler error because &lt;em&gt;Object&lt;/em&gt; doesn&amp;rsquo;t have a &lt;em&gt;Key&lt;/em&gt; property.&lt;/p&gt;
&lt;p&gt;The generic constraint tells the C# compiler that a &lt;em&gt;TWidget&lt;/em&gt; has to be a &lt;em&gt;Widget&lt;/em&gt;, and since a &lt;em&gt;Widget&lt;/em&gt;&amp;nbsp;has to have a &lt;em&gt;Key&lt;/em&gt; property the C# compiler is happy to compile the code.&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/OdeToCode?a=Bz8Z6VMLIzU:GK1SmZnCph0:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/OdeToCode?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;</description><pubDate>Tue, 18 Jun 2013 09:12:00 Z</pubDate></item><item><guid isPermaLink="true">http://odetocode.com/blogs/scott/archive/2013/06/17/bootstrap-dialogs-and-promises-in-angularjs-tests.aspx</guid><link>http://odetocode.com/blogs/scott/archive/2013/06/17/bootstrap-dialogs-and-promises-in-angularjs-tests.aspx</link><author>scott@OdeTocode.com</author><title>Bootstrap Dialogs and Promises In AngularJS Tests</title><description>&lt;p&gt;&lt;img style="float: right; margin: 0px 0px 5px 5px; display: inline" align="right" src="http://odetocode.com/images2/Windows-Live-Writer/Angular-Abstractions-The-Application_F661/image_3.png"&gt;The &lt;a href="https://github.com/angular/angular.js/tree/master/src/ngMock"&gt;angular-mocks&lt;/a&gt; library we’ve been using in the &lt;a href="http://odetocode.com/blogs/scott/archive/2013/06/11/angularjs-tests-with-an-http-mock.aspx"&gt;previous posts&lt;/a&gt; make unit tests easier to write and includes some built-in mocks for Angular services like $browser, $log, and $httpBackend. However, mocks aren’t available for every service, and there are certainly other services you’ll want to fake to isolate code in a unit test. &lt;/p&gt; &lt;p&gt;For example, &lt;a href="http://mgcrea.github.io/angular-strap/"&gt;AngularStrap&lt;/a&gt; offers directives and services for integrating AngularJS with &lt;a href="http://twitter.github.io/bootstrap/"&gt;Bootstrap&lt;/a&gt;. One of the services is the $modal service that allows you to programmatically launch a modal dialog from inside a view model. Here is a controller that launches the dialog as soon as the controller itself is created. &lt;/p&gt;&lt;pre class="brush: js; gutter: false; toolbar: false;"&gt;(function (module) {
    "use strict";

    var severSelectDialog;
    var initServerSelectDialog = function ($modal, $scope) {
        return $modal(
            {
                template: '_serverSelect.html',
                persist: true, show: false, scope: $scope
            });
    };

    var showSelectServerDialog = function () {
        severSelectDialog.then(function (modal) { modal.modal("show"); });
    };

    var MainController = function ($scope, $modal) {
        severSelectDialog = initServerSelectDialog($modal, $scope);
        showSelectServerDialog();
        
        // ...
    };
    MainController.$inject = ["$scope", "$modal"];

    module.controller("MainController", MainController);

}(angular.module("mongoMagno")));
&lt;/pre&gt;
&lt;p&gt;Using $modal to open a dialog is a two step process. First you call $modal and get a promise, then you call “show” on the modal object resolved by the promise (the promise exists because the markup template&amp;nbsp; for the modal might be asynchronously loaded from the server). &lt;/p&gt;
&lt;p&gt;Using Jasmine, if you wanted to unit test the controller to ensure the controller interacts with the $modal appropriately, you could use a spy with some fakes like so:&lt;/p&gt;&lt;pre class="brush: js; gutter: false; toolbar: false;"&gt;describe('MainController', function() {

    var fakeModal = {
        command: null,
        modal: function(command) {
            this.command = command;
        }
    };

    var fakeModalPromise = {
        then: function(callback) {
            callback(fakeModal);
        }
    };

    var $modal, scope;
    beforeEach(angular.mock.inject(function($rootScope, $controller) {
        fakeModal.command = null;
        $modal = jasmine.createSpy("$modal").andReturn(fakeModalPromise);
        scope = $rootScope.$new();
        $controller('MainController', {
            $scope: scope,
            $modal: $modal
        });
    }));

    it("should show server connect dialog when launched", function() {
        expect(fakeModal.command).toBe("show");
    });
});
&lt;/pre&gt;
&lt;p&gt;Another approach is not to use a fake promise but a real promise created by the Angular $q service. &lt;/p&gt;&lt;pre class="brush: js; gutter: false; toolbar: false;"&gt;describe('MainController', function() {

    var FakeModal = function() {

        this.modal = function(command) {
            this.command = command;
        };
    };

    var scope, fakeModal;
    beforeEach(angular.mock.inject(function($rootScope, $controller, $q) {
        var deferred = $q.defer();
        fakeModal = new FakeModal();
        deferred.resolve(fakeModal);

        $modal = jasmine.createSpy("$modal").andReturn(deferred.promise);
        scope = $rootScope.$new();
        $scope.$apply(function() {
            $controller('MainController', {
                $scope: scope,
                $modal: $modal
            });
        });
    }));

    it("should show connect dialog when launched", function() {
        expect(fakeModal.command).toBe("show");
    });
});
&lt;/pre&gt;
&lt;p&gt;This approach requires a call to $scope.$apply (a real promise from the $q service doesn’t fully resolve until an $apply cycle executes). &lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/OdeToCode?a=4eLlWOt4Awk:-mWXhRjbous:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/OdeToCode?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;</description><pubDate>Mon, 17 Jun 2013 09:12:00 Z</pubDate></item><item><guid isPermaLink="true">http://odetocode.com/blogs/scott/archive/2013/06/11/angularjs-tests-with-an-http-mock.aspx</guid><link>http://odetocode.com/blogs/scott/archive/2013/06/11/angularjs-tests-with-an-http-mock.aspx</link><author>scott@OdeTocode.com</author><title>AngularJS Tests With An HTTP Mock</title><description>&lt;p&gt;&lt;img style="float: right; margin: 0px 0px 5px 5px; display: inline" align="right" src="http://odetocode.com/images2/Windows-Live-Writer/Angular-Abstractions-The-Application_F661/image_3.png"&gt;In the &lt;a href="http://odetocode.com/blogs/scott/archive/2013/06/10/simple-unit-tests-with-angularjs.aspx"&gt;last post&lt;/a&gt; we tested a simple controller, so now let’s look at a controller that likes to communicate over the network. &lt;/p&gt;&lt;pre class="brush: js; gutter: false; toolbar: false;"&gt;(function (module) {

    var MoviesController = function ($scope, $http) {

        $http.get("/api/movies")
            .then(function (result) {
                $scope.movies = result.data;
            });
    };

    module.controller("MoviesController",
        ["$scope", "$http", MoviesController]);

}(angular.module("myApp")));
&lt;/pre&gt;
&lt;p&gt;If you want a unit test to execute without network communication there are a couple options. You could refactor the controller to use a custom service to fetch movies instead of using $http directly. Then in a unit test it would be easy to provide a fake service that returns pre-canned responses.&lt;/p&gt;
&lt;p&gt;Another option is to use &lt;a href="https://github.com/angular/angular.js/tree/master/src/ngMock"&gt;angular-mocks&lt;/a&gt;. Angular mocks includes a programmable fake $httpBackend that replaces the real $httpBackend service. It is important to note that &lt;strong&gt;$httpBackend is not the same as the $http service&lt;/strong&gt;. The $http service &lt;strong&gt;uses&lt;/strong&gt; $httpBackend to send HTTP messages. In a unit test, we’ll use the real $http service, but a fake $httpBackend programmed to respond in a specific way. &lt;/p&gt;
&lt;p&gt;Here is one approach:&lt;/p&gt;&lt;pre class="brush: js; gutter: false; toolbar: false;"&gt;describe("myApp", function () {

    beforeEach(module('myApp'));

    describe("MoviesController", function () {

        var scope, httpBackend;
        beforeEach(inject(function ($rootScope, $controller, $httpBackend, $http) {
            scope = $rootScope.$new();
            httpBackend = $httpBackend;
            httpBackend.when("GET", "/api/movies").respond([{}, {}, {}]);
            $controller('MoviesController', {
                $scope: scope,
                $http: $http
            });
        }));

        it("should have 3 movies", function () {
            httpBackend.flush();
            expect(scope.movies.length).toBe(3);
        });
    });
});
&lt;/pre&gt;
&lt;p&gt;In the above test, $httpBackend is programmed (with the &lt;em&gt;when&lt;/em&gt; method) to respond to a GET request with three objects (empty objects, since the controller in this example never uses the data, but only assigns the response to the model). &lt;/p&gt;
&lt;p&gt;For the data to arrive in the model, the test needs to call the &lt;em&gt;flush&lt;/em&gt; method. Flush will respond to all requests with the programmed responses. The flush method will also verify there are no outstanding expectations. Writing tests with expectations is a little bit different.&lt;/p&gt;&lt;pre class="brush: js; gutter: false; toolbar: false;"&gt;describe("myApp", function () {

    beforeEach(module('myApp'));

    describe("MoviesController", function () {

        var scope, httpBackend, http, controller;
        beforeEach(inject(function ($rootScope, $controller, $httpBackend, $http) {
            scope = $rootScope.$new();
            httpBackend = $httpBackend;
            http = $http;
            controller = $controller;
            httpBackend.when("GET", "/api/movies").respond([{}, {}, {}]);
        }));
      
        it('should GET movies', function () {
            httpBackend.expectGET('/api/movies');
            controller('MoviesController', {
                $scope: scope,
                $http: http
            });
            httpBackend.flush();
        });
    });
});
&lt;/pre&gt;
&lt;p&gt;The expectation in the above code is registered with the &lt;em&gt;expectGET&lt;/em&gt; method. When the test calls &lt;em&gt;flush&lt;/em&gt;, &lt;em&gt;flush&lt;/em&gt; will fail the test if the controller did not make all of the &lt;em&gt;expect&lt;/em&gt; calls. Of the two tests in this post, I prefer the first style. Testing with expectations is the same as interaction testing with mocks, which I’ve learned to shy away from because interaction testing tends to be brittle. &lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/OdeToCode?a=fiPw2o1s8cY:k8zwWWRFQ3Q:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/OdeToCode?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;</description><pubDate>Tue, 11 Jun 2013 09:12:00 Z</pubDate></item><item><guid isPermaLink="true">http://odetocode.com/blogs/scott/archive/2013/06/10/simple-unit-tests-with-angularjs.aspx</guid><link>http://odetocode.com/blogs/scott/archive/2013/06/10/simple-unit-tests-with-angularjs.aspx</link><author>scott@OdeTocode.com</author><title>Simple Unit Tests With AngularJS</title><description>&lt;p&gt;&lt;img style="float: right; margin: 0px 0px 5px 5px; display: inline" align="right" src="http://odetocode.com/images2/Windows-Live-Writer/Angular-Abstractions-The-Application_F661/image_3.png"&gt;One of the benefits of using AngularJS is the ability to unit test the JavaScript code in a complex application. Unit testing is incredibly easy for trivial cases when controllers and models are declared in global scope. However unit testing is slightly more challenging for objects defined inside of Angular modules because of the need to bootstrap modules, work with a dependency injector, and deal with the subtleties of nested functional code.&amp;nbsp; &lt;/p&gt; &lt;p&gt;Let’s try to test the following controller defined in a module:&lt;/p&gt;&lt;pre class="brush: js; gutter: false; toolbar: false;"&gt;(function (app) {
    
    var SimpleController = function ($scope) {
     
        $scope.x = 3;
        $scope.y = 4;
        $scope.doubleIt = function () {
            $scope.x *= 2;
            $scope.y *= 2;
        };
    };
    
    app.controller("SimpleController", 
             ["$scope", SimpleController]);
    
}(angular.module("myApp")));
&lt;/pre&gt;
&lt;p&gt;We’ll be using &lt;a href="https://github.com/angular/angular.js/tree/master/src/ngMock"&gt;AngularJS mocks&lt;/a&gt; and Jasmine in an HTML page, which requires the following scripts:&lt;/p&gt;
&lt;p&gt;- jasmine.js&lt;/p&gt;
&lt;p&gt;- jasmine-html.js&lt;/p&gt;
&lt;p&gt;- angular.js&lt;/p&gt;
&lt;p&gt;- angular-mocks.js&lt;/p&gt;
&lt;p&gt;- simpleController.js (where the controller lives)&lt;/p&gt;
&lt;p&gt;It’s important to &lt;strong&gt;include the Jasmine scripts before including angular-mocks&lt;/strong&gt;, as angular-mocks will enable some additional features when Jasmine is present (notably the helper methods &lt;em&gt;module&lt;/em&gt; and &lt;em&gt;inject&lt;/em&gt;).&lt;/p&gt;&lt;pre class="brush: js; gutter: false; toolbar: false;"&gt;describe("myApp", function() {

    beforeEach(module('myApp'));

    describe("SimpleController", function() {

        var scope;
        beforeEach(inject(function($rootScope, $controller) {
            scope = $rootScope.$new();
            $controller("SimpleController", {
                $scope: scope
            });
        }));

        it("should double the numbers", function() {
            scope.doubleIt();
            expect(scope.x).toBe(6);
        });
    });
});
&lt;/pre&gt;
&lt;p&gt;The &lt;em&gt;module&lt;/em&gt; method used in the first &lt;em&gt;beforeEach&lt;/em&gt; (which you can also invoke as &lt;em&gt;angular.mocks.module&lt;/em&gt;) will initialize and configure the myApp module and its dependencies. &lt;/p&gt;
&lt;p&gt;The &lt;em&gt;inject&lt;/em&gt; method in the second &lt;em&gt;beforeEach&lt;/em&gt; (&lt;em&gt;angular.mocks.inject&lt;/em&gt;) takes a function that requires dependencies. Behind the scenes, the &lt;em&gt;inject&lt;/em&gt; method will set up an $injector and use it to invoke the function with the right dependencies. In this test, we need the application’s $rootScope object and the $controller service. We are going to use the $controller service to have complete oversight over the instantiation of the SimpleController and keep a scope object around that we can write asserts against. &lt;/p&gt;
&lt;p&gt;Once the setup code is done, the &lt;em&gt;it&lt;/em&gt; tests are relatively easy to write (and read). The trick is figuring out what to inject, what to instantiate directly, and (a topic for future posts) what to mock or fake by hand. &lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/OdeToCode?a=S2TbQDCmAbk:FH3qGyerUFY:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/OdeToCode?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;</description><pubDate>Mon, 10 Jun 2013 09:12:00 Z</pubDate></item><item><guid isPermaLink="true">http://odetocode.com/blogs/scott/archive/2013/06/07/highlighting-the-active-menu-item-in-angularjs.aspx</guid><link>http://odetocode.com/blogs/scott/archive/2013/06/07/highlighting-the-active-menu-item-in-angularjs.aspx</link><author>scott@OdeTocode.com</author><title>Highlighting the Active Menu Item In AngularJS</title><description>&lt;p&gt;&lt;img style="float: right; margin: 0px 0px 5px 5px; display: inline;" src="http://odetocode.com/images2/Windows-Live-Writer/Angular-Abstractions-The-Application_F661/image_3.png" alt="" align="right" /&gt;Most applications feature menu items that will need to appear selected at the appropriate time.&lt;/p&gt;
&lt;p&gt;How to do this with Angular?&lt;/p&gt;
&lt;p&gt;There are many different approaches, but ideally we&amp;rsquo;ll do this with a directive, since directives are responsible for DOM manipulation, and &amp;ldquo;selecting&amp;rdquo; a menu item will require some manipulation of the classes on an element. The goal would be to make it as easy as possible from a view:&lt;/p&gt;
&lt;pre class="brush: xml; gutter: false; toolbar: false;"&gt;&amp;lt;nav&amp;gt;
    &amp;lt;ul data-active-menu="selected"&amp;gt;
        &amp;lt;li&amp;gt;&amp;lt;a href="#/details?q=foo"&amp;gt;Details&amp;lt;/a&amp;gt;&amp;lt;/li&amp;gt;
        &amp;lt;li&amp;gt;&amp;lt;a href="#/test"&amp;gt;Summary&amp;lt;/a&amp;gt;&amp;lt;/li&amp;gt;
        ...
    &amp;lt;/ul&amp;gt;
&amp;lt;/nav&amp;gt;
&lt;/pre&gt;
&lt;p&gt;In the above code, the &lt;em&gt;data-active-menu&lt;/em&gt; attribute should allow a custom directive to jump in and manipulate the styles of the elements inside by adding &amp;ldquo;selected&amp;rdquo; as a class to the active link, and removing the class from all other links.&lt;/p&gt;
&lt;p&gt;The directive code itself would look like this:&lt;/p&gt;
&lt;pre class="brush: js; gutter: false; toolbar: false;"&gt;(function () {
    
    var makeWatcher = function(location) {
        return function() {
            return location.url();
        };
    };

    var makeLinkUpdater = function(links, className) {
        return function (value) {
            angular.forEach(links, function(link) {
                link = angular.element(link);
                if (/\#(\/[^\/]+)/.exec(link.attr("href"))[1] == value) {
                    link.addClass(className);
                } else {
                    link.removeClass(className);
                }
            });
        };
    };

    var activeMenu = function($location) {

        var link = function(scope, element, attrs) {
            var links = element.find("a");
            var className = attrs.activeMenu;
            scope.$watch(makeWatcher($location),
                         makeLinkUpdater(links, className));
        };

        return {
            link:link
        };
    };
    activeMenu.$injector = ["$location"];
    
    angular.module("testApp")
           .directive("activeMenu", activeMenu);
}());
&lt;/pre&gt;
&lt;p&gt;By taking a dependency on the $location service in AngularJS, the directive can both watch for when the location changes, and compare the current location to the href in the menu items. Matching hrefs get the class specified in the data-menu-active attribute. Easy, reusable, and keeps more boilerplate code out of the controllers.&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/OdeToCode?a=L1rnB0rJiaw:Qf5KetlrIkk:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/OdeToCode?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;</description><pubDate>Fri, 07 Jun 2013 09:12:00 Z</pubDate></item><item><guid isPermaLink="true">http://odetocode.com/blogs/scott/archive/2013/06/06/decorating-angularjs-services.aspx</guid><link>http://odetocode.com/blogs/scott/archive/2013/06/06/decorating-angularjs-services.aspx</link><author>scott@OdeTocode.com</author><title>Decorating AngularJS Services</title><description>&lt;p&gt;&lt;img style="float: right; margin: 0px 0px 10px 10px; display: inline;" src="http://odetocode.com/images2/Windows-Live-Writer/Angular-Abstractions-The-Application_F661/image_3.png" alt="" align="right" /&gt;The &lt;a href="http://odetocode.com/blogs/scott/archive/2013/06/05/angularjs-abstractions-services.aspx"&gt;last post&lt;/a&gt; demonstrated a service to wrap geolocation APIs in the browser.&lt;/p&gt;
&lt;p&gt;At some point the application might need to add some logging before and after the geolocation calls. One way to do this is to add code to the geo service directly, but AngularJS also allows us to register decorators for any service (including the built-in Angular services).&lt;/p&gt;
&lt;p&gt;Decorator is a wonderful pattern for extensibility since the original object doesn&amp;rsquo;t need to anything about the decoration, and neither does the consumer of the service.&lt;/p&gt;
&lt;p&gt;Here is a quick example of creating a decorator for the geo service. The decorator will log the amount of time taken for the geo service to return a result. When creating a decorator, AngularJS will pass the original service as the $delegate parameter.&lt;/p&gt;
&lt;pre class="brush: js; gutter: false; toolbar: false;"&gt;(function() {
        
    var geoDecorator = function($delegate) {
        var locate = function() {
            var start = new Date();
            var result = $delegate.locate();
            result.always(function () {
                console.log("Geo location took: " + (new Date() - start) + "ms");
            });
            return result;
        };

        return {
          locate: locate  
        };
    };

    var testApp = angular.module("testApp");
    testApp.config(["$provide", function ($provide) {
        $provide.decorator("geo", geoDecorator);
    }]);
    
}());
&lt;/pre&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/OdeToCode?a=kwS8q0_SNIs:b_doi9X-_bg:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/OdeToCode?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;</description><pubDate>Thu, 06 Jun 2013 09:12:00 Z</pubDate></item><item><guid isPermaLink="true">http://odetocode.com/blogs/scott/archive/2013/06/05/angularjs-abstractions-services.aspx</guid><link>http://odetocode.com/blogs/scott/archive/2013/06/05/angularjs-abstractions-services.aspx</link><author>scott@OdeTocode.com</author><title>AngularJS Abstractions: Services</title><description>&lt;p&gt;&lt;img style="float: right; margin: 0px 0px 5px 5px; display: inline" align="right" src="http://odetocode.com/images2/Windows-Live-Writer/Angular-Abstractions-The-Application_F661/image_3.png"&gt;At first glance, services in AngularJS are a catch-all destination for any code that doesn’t fall into one of the other primary abstractions in the framework. If it’s not a controller, filter, directive, or model,&amp;nbsp; it must be a service. One reason to think to think this way is because one can interpret the word “service” to mean anything in software. However, services in Angular have capabilities and behaviors that make them well suited for specific jobs. &lt;/p&gt; &lt;h3&gt;Services As Application Helpers&lt;/h3&gt; &lt;p&gt;Controllers, applications, and even other services can take a dependency on 0 or more services, meaning services can be a convenient location for code that is used in different places throughout an application. For example, if two controllers both require some algorithmic logic to make a decision, it would be better to place the logic inside a service that both controllers can use than have the code duplicated in two different controllers. &lt;/p&gt; &lt;h3&gt;Services As Singletons&lt;/h3&gt; &lt;p&gt;AngularJS will manage services to make sure there is only one instance of a service per application. This makes services a convenient storage location for data that needs to stick around (controllers and their models can come and go as views are loaded and unloaded in the DOM). &lt;/p&gt; &lt;h3&gt;Services As Communication Hubs&lt;/h3&gt; &lt;p&gt;AngularJS provides a framework to achieve a separation of concerns and a the various components have no knowledge of each other. Since services can be injected into almost anything (controllers, directives, filters, and even other services), a service can play the role of a mediator or event aggregator for other components to communicate in a loosely coupled manner. &lt;/p&gt; &lt;h3&gt;Services As Injectable Dependencies&lt;/h3&gt; &lt;p&gt;Perhaps the biggest reason to put code into a service is because services are injected into other components, meaning components maintain a loose coupling and any particular service can be replaced during a unit test. AngularJS itself provides many services that fall into this category. There is the $http service (for network communication),&amp;nbsp; the $window service (a wrapper for the global window object), the $log service, and others. &lt;/p&gt; &lt;h3&gt;What Isn’t A Service?&lt;/h3&gt; &lt;p&gt;There is plenty of vanilla JavaScript code you can write for an AngularJS application that doesn’t have to live inside an AngularJS abstraction. Model and view model definitions, for example, could live outside of any controller or service. Controllers could instantiate models, obviously, and services could hold references and vice versa. My candidates for services generally fall into one of the previous 4 categories, and as models are easy to test without test doubles, they don’t need to be injected and hence don’t need to be considered a service themselves, although it is certainly reasonable to make a service responsible for fetching a model from some unknown data source. &lt;/p&gt; &lt;h3&gt;How To Create A Service?&lt;/h3&gt; &lt;p&gt;One of the confusing areas of AngularJS revolves around the APIs for&amp;nbsp; creating a service, since there are no fewer than 6 ways to register a service and the obvious API choice, a method named &lt;em&gt;service&lt;/em&gt;, probably shouldn’t be your first choice. The one that can adapt to just about any scenario is the &lt;em&gt;factory&lt;/em&gt; method, which when used on a module object looks like something that would define a factory function for the module, but in fact is defining a factory function for a service (another unfortunate point of confusion). &lt;/p&gt; &lt;p&gt;As an example, here is a service to wrap the geolocation APIs of&amp;nbsp; the browser:&lt;/p&gt;&lt;pre class="brush: js; gutter: false; toolbar: false;"&gt;(function () {

    var geo = function ($q, $rootScope) {

        var apply = function () {
            $rootScope.$apply();
        };

        var locate = function () {
            var defer = $q.defer(); 
            navigator.geolocation.getCurrentPosition(
                function (position) {
                    defer.resolve(position);
                    apply();
                },
                function(error) {
                    defer.reject(error);
                    apply();
                });
            return defer.promise;
        };

        return {
            locate: locate
        };
    };

    geo.$inject = ["$q", "$rootScope"];

    angular.module("testApp")
           .factory("geo", geo);

}());
&lt;/pre&gt;
&lt;p&gt;The factory method takes a function that AngularJS will invoke to create the service instance. This geo service makes use of the $q service provided by Angular to create promises for the asynchronous delivery of latitude and longitude. Somewhere else in the app, a controller can take a dependency on the geo service and use it to find the user’s position. &lt;/p&gt;&lt;pre class="brush: js; gutter: false; toolbar: false;"&gt;(function () {

    var TestController = function ($scope, geo) {

        geo.locate()
           .then(function (position) {
                $scope.position = position;
            });
    };

    TestController.$inject = ["$scope", "geo"];

    angular.module("testApp")
           .controller("TestController", TestController);

}());
&lt;/pre&gt;
&lt;h3&gt;Summary&lt;/h3&gt;
&lt;p&gt;Services are an important part of any AngularJS application. The built-in services in the framework make code more testable, and custom services can provide an abstraction to make code easier to maintain. &lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/OdeToCode?a=hzL-zY-x3e0:iuZGdj03hx4:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/OdeToCode?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;</description><pubDate>Wed, 05 Jun 2013 09:12:00 Z</pubDate></item><item><guid isPermaLink="true">http://odetocode.com/blogs/scott/archive/2013/05/28/angularjs-abstractions-directives.aspx</guid><link>http://odetocode.com/blogs/scott/archive/2013/05/28/angularjs-abstractions-directives.aspx</link><author>scott@OdeTocode.com</author><title>AngularJS Abstractions: Directives</title><description>&lt;p&gt;&lt;img style="float: right; margin: 0px 0px 5px 10px; display: inline;" src="http://odetocode.com/images2/Windows-Live-Writer/Angular-Abstractions-The-Application_F661/image_3.png" alt="" align="right" /&gt;Directives are one of the lynchpins that make AngularJS work, and also make the framework nice to work with.&lt;/p&gt;
&lt;p&gt;Directives are the attributes Angular searches for in the markup when the DOM is loaded, attributes like ng-app, ng-controller, and ng-click. You can also use directives to create custom elements, like &amp;lt;my-widget&amp;gt;, but doing so depends on how much value you place in having your raw source validated by an HTML validator.&lt;/p&gt;
&lt;p&gt;If validation is high on your list, there are HTML 5 compliant approaches to using directives, including data- prefixing attribute directives (use data-ng-controller instead of ng-controller, for example, and Angular still works).&lt;/p&gt;
&lt;h3&gt;What Are They Really?&lt;/h3&gt;
&lt;p&gt;From an abstraction perspective, directives form an anti-corruption layer between a model and a view. Directives are where you can listen for changes in a model value and then go manipulate the DOM. Directives allow models to change the content and presentation of a view without the model getting bogged down by the DOM manipulation code. The model stays clean, testable, and plain.&lt;/p&gt;
&lt;p&gt;Here&amp;rsquo;s an example of a custom &amp;ldquo;myShow&amp;rdquo; directive(note that AngularJS already has an ngShow directive to do this job, but this is an easy example to understand).&lt;/p&gt;
&lt;p&gt;The purpose of the myShow attribute is to show or hide a DOM element based on the truthiness of a model value.&lt;/p&gt;
&lt;p&gt;First, the markup:&lt;/p&gt;
&lt;pre class="brush: xml; gutter: false; toolbar: false;"&gt;&amp;lt;div data-ng-controller="TestController"&amp;gt;
    
    &amp;lt;div data-my-show="model.visible"&amp;gt;
        {{model.message}}
    &amp;lt;/div&amp;gt;
            
    &amp;lt;button data-ng-click="model.toggleVisible()"&amp;gt;Click me!&amp;lt;/button&amp;gt;

&amp;lt;/div&amp;gt;
&lt;/pre&gt;
&lt;p&gt;Notice the data-my-show attribute on the first inner div. The attribute value is set to &amp;ldquo;model.visible&amp;rdquo;.&lt;/p&gt;
&lt;p&gt;Here is the controller and model for the scenario:&lt;/p&gt;
&lt;pre class="brush: js; gutter: false; toolbar: false;"&gt;(function () {

    var model = {
        visible: false,
        message: "Surprise!",
        toggleVisible: function () {
            this.visible = !this.visible;
        }
    };

    var TestController = function ($scope) {
        $scope.model = model;
    };

    TestController.$inject = ["$scope"];

    angular.module("testApp")
           .controller("TestController", TestController);

}());
&lt;/pre&gt;
&lt;p&gt;All that&amp;rsquo;s needed now is the code for the my-show directive:&lt;/p&gt;
&lt;pre class="brush: js; gutter: false; toolbar: false;"&gt;(function () {

    var myShow = function() {
        return {
            restrict: "A",
            link: function(scope, element, attrs) {
                scope.$watch(attrs.myShow, function(value) {
                    element.css("display", value ? "" : "none");
                });
            }
        };
    };

    angular.module("testApp")
           .directive("myShow", myShow);
}());
&lt;/pre&gt;
&lt;p&gt;The naming conventions applied by AngularJS allow the directive registered as &amp;ldquo;myShow&amp;rdquo; to be applied in markup as &lt;em&gt;data-my-show&lt;/em&gt;, as well as &lt;em&gt;my-show&lt;/em&gt; and a few other variations.&amp;nbsp;&lt;/p&gt;
&lt;p&gt;The directive itself is setup by a function that returns a &amp;ldquo;directive definition object&amp;rdquo; (let&amp;rsquo;s call it the DDO). The DDO has to have a few members in place for the directive to work, but this sample only uses a couple members: &lt;em&gt;restrict&lt;/em&gt; and &lt;em&gt;link&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;The &lt;em&gt;restrict&lt;/em&gt; property specifies where the directive is valid (E for element, A for attribute, C for class, M for comment). Since the default for &lt;em&gt;restrict &lt;/em&gt;is &amp;ldquo;A&amp;rdquo;, this property could be omitted.&lt;/p&gt;
&lt;p&gt;The &lt;em&gt;link&lt;/em&gt; function is responsible for making things happen by setting up watches to listen for changes in the model.&amp;nbsp; Angular invokes the &lt;em&gt;link&lt;/em&gt; function and gives it the model (&lt;em&gt;scope&lt;/em&gt;), the &lt;em&gt;element&lt;/em&gt; (effectively a jQuery wrapped reference to the DOM element), and an &lt;em&gt;attrs&lt;/em&gt; parameter containing the attributes of the element. Asking for &lt;em&gt;attrs.myShow&lt;/em&gt; will return &amp;ldquo;model.visible&amp;rdquo;, since that is the attribute value specified in the markup.&lt;/p&gt;
&lt;p&gt;The link function in this example uses &lt;em&gt;scope.$watch &lt;/em&gt;to listen for changes in the specified model value. $watch is a good topic for a future post, but for now we can say if the model changes it&amp;rsquo;s visible property from false to true, the framework invokes the listener function passed as the second parameter to &lt;em&gt;$watch&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;The listener function in this sample sets the &lt;em&gt;display&lt;/em&gt; property of the element to an empty string or &amp;ldquo;none&amp;rdquo; to toggle visibility of the element. The value parameter in the function is the recently changed model value, the value the directive set up to $watch.&lt;/p&gt;
&lt;h3&gt;Where Are We?&lt;/h3&gt;
&lt;p&gt;This sample doesn&amp;rsquo;t show the full capabilities of a directive, which can also load additional markup from a string or a URL, as well as other nifty features.&amp;nbsp; We&amp;rsquo;ll cycle back to more advanced features in a future post.&lt;/p&gt;
&lt;p&gt;Although custom directives can require&amp;nbsp; more code in a project compared to using DOM manipulation inside a controller, the advantage of having a directive in place is in keeping the models and controllers simple. Plus, once written, most directives can be parameterized and reused in different places and multiple applications.&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/OdeToCode?a=HhnQMSGhXjM:sdmFCJ_IUBU:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/OdeToCode?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;</description><pubDate>Tue, 28 May 2013 09:12:00 Z</pubDate></item><item><guid isPermaLink="true">http://odetocode.com/blogs/scott/archive/2013/05/27/using-elemmatch-in-a-mongodb-query.aspx</guid><link>http://odetocode.com/blogs/scott/archive/2013/05/27/using-elemmatch-in-a-mongodb-query.aspx</link><author>scott@OdeTocode.com</author><title>Using elemMatch in a MongoDB Query</title><description>&lt;p&gt;I introduced a latent bug in some code recently while trying to find documents with a specific set of values embedded inside an array. For example, consider the following documents:&lt;/p&gt;
&lt;pre class="brush: plain; gutter: false; toolbar: false;"&gt;{
    "name" : "Thing1",
    "children" : [  
        { "name" : "C1", "value" : "A" },
        { "name" : "C2", "value" : "B" },
        { "name" : "C3", "value" : "C" }]
}, {
    "name" : "Thing2",
    "children" : [
        { "name" : "C3", "value" : "A" },
        { "name" : "C4", "value" : "B" },
        { "name" : "C5", "value" : "C" }]
}, {
    "name": "Thing3",
    "children": [
        { "name": "C5", "value": "A" },
        { "name": "C6", "value": "B" },
        { "name": "C7", "value": "C" }]
}
&lt;/pre&gt;
&lt;p&gt;Let&amp;rsquo;s say we only want documents with a child entry that has a name of C3 &lt;em&gt;AND&lt;/em&gt; a value of C (only Thing1 should match this criteria because of the last child in its array). It&amp;rsquo;s tempting to write a query with an AND clause and feel good about the C# code.&lt;/p&gt;
&lt;pre class="brush: csharp; gutter: false; toolbar: false;"&gt;var query = things.Find(
    Query.And(
        Query.EQ("children.name", "C3"),
        Query.EQ("children.value", "C")
    ));
&lt;/pre&gt;
&lt;p&gt;But MongoDB, being document oriented, interprets the query as &amp;ldquo;give me all the documents that have &lt;em&gt;any&lt;/em&gt; child with a name of C3, &lt;em&gt;and&lt;/em&gt; &lt;em&gt;any&lt;/em&gt; child with a value of C. In other words, the name and value combination don&amp;rsquo;t need to match inside the same array element. A quick test from the shell can verify the behavior.&lt;/p&gt;
&lt;pre class="brush: plain; gutter: false; toolbar: false;"&gt;&amp;gt; db.things.find({"children.name":"C3", "children.value":"C"},{name:1, _id:0})
{ "Name" : "Thing1" }
{ "Name" : "Thing2" }
&lt;/pre&gt;
&lt;p&gt;The $elemMatch query operator tells Mongo to only match documents when at least one element in the array satisfies the entire criteria.&lt;/p&gt;
&lt;pre class="brush: csharp; gutter: false; toolbar: false;"&gt;var query = things.Find(
    Query.ElemMatch("children",
        Query.And(
            Query.EQ("name", "C3"), 
            Query.EQ("value", "C")
        )
     ));
&lt;/pre&gt;
&lt;p&gt;The shell will verify that we only get the Thing1 we want:&lt;/p&gt;
&lt;pre class="brush: plain; gutter: false; toolbar: false;"&gt;&amp;gt; db.things.find({ children: { $elemMatch : { name:"C3", value:"C"}}}, {name:1, _id:0})
{ "Name" : "Thing1" }
&lt;/pre&gt;
&lt;p&gt;Not an easy bug to catch in a test without a robust set of test data.&lt;/p&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/OdeToCode?a=ef8bgfnV5H4:-UMTtoQeaiU:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/OdeToCode?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;</description><pubDate>Mon, 27 May 2013 09:12:00 Z</pubDate></item></channel></rss>
