OdeToCode IC Logo

Forms With AngularJS

Thursday, February 21, 2013

Continuing to reach for feature parity with my original jQuery with ASP.NET Web API sample, I need to have the ability to create a new video. 

The original sample caught the form submit event and serialized form data for an AJAX submission to the web server.

With AngularJS I only need to bind some form elements to the model (using the ng-model directive), and bind a click event (with the ng-click directive).

<form>
    <input type="hidden" ng-model="editableVideo.Id"/>
    <label>Title:</label>            
    <input type="text" ng-model="editableVideo.Title" required />
    <label>Length</label>
    <input type="number" ng-model="editableVideo.Length" min="1" max="360" />
    <input type="submit" value="Save" ng-click="saveVideo()" />
</form>

Note there is also an ngSubmit directive, but Angular will prevent the default form submission if I have only one or the other. When the user clicks save, I just need to post the new video information to the Web API.  The controller code now looks like the following:

var VideoController = function ($scope, $http) {

    var serviceUrl = "/api/videos";

    var blankVideo = {
        Id: "",
        Title: "",
        Length: 75
    };

    var refreshVideos = function() {
        $http.get(serviceUrl).success(function (data) {
            $scope.videos = data;
        });                
    };

    $scope.isEditVisible = false;

    $scope.showEdit = function () {
        $scope.isEditVisible = true;
        $scope.editableVideo = angular.copy(blankVideo);
    };

    $scope.saveVideo = function() {
        $scope.isEditVisible = false;
        $http.post(serviceUrl, $scope.editableVideo)
             .success(function (video) {
                 $scope.videos.push(video);
             });
    };

    refreshVideos();
};

Notice it is easy to keep private methods and data inside a controller.

Next I need the ability to delete and edit existing videos, and then the sample will behave exactly like the original "jQuery only" sample. We'll look at those scenarios next.