AngularJS Initialization Demo (basic)

see http://jsfiddle.net/gesellix/xxKjw/ for more details

by Tobias Gesellchen

HTML

<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.1.5/angular.min.js"></script>
<div ng-app="myModule" class="wrapper">
    <h2>AngularJS Initialization Demo</h2>
    <p>For details see <a href="http://wp.me/p1E7sK-hn" target="_blank">article</a>
    <div ng-controller="simpleController" class="left">
        <h3>basic example</h3>
        <p ng-show="options.length == 0">loading options...</p>
        <select ng-show="options.length !== 0"
        ng-model="selectedOption"
        ng-options="option.value as option.name for option in options">
        </select>
        
        <div class="log">
            log:
            <ul>
                <li ng-repeat="entry in logentries">{{entry}}</li>
            </ul>
        </div>
    </div>
</div>

CSS

div.left,
div.right {
    position: relative;
    float: left;
}
.wrapper {
    width: 100%;
}
.left {
    width: 40%;
}
.right {
    width: 40%;
}
.log {
    margin-top: 10px;
}
ul {
    list-style-type: none;
}

JavaScript

var myModule = angular.module('myModule', []);

myModule.service('myService', function($http) {
    $http.defaults.headers.post['Content-Type'] = "application/x-www-form-urlencoded; charset=UTF-8";
    this.getOptions = function() {
        return $http({
            "method": "post",
            "url": '/echo/json/', 
            "data": "delay=3&json=" + encodeURI(JSON.stringify({
                options: [
                    {name:'entry1', value:0},
                    {name:'entry2', value:1},
                    {name:'entry3', value:2}]
            }))
        });
    };
});

myModule.controller('simpleController', function($scope, myService) {
    $scope.selectedOption = null;
    $scope.options = [];
    $scope.logentries = [];
    myService.getOptions().then(function(result) {
        $scope.options = result.data.options;
        $scope.selectedOption = 0;
    });
    $scope.$watch('selectedOption', function(newValue, oldValue) {
        // handle selection change ...
        console.log("selection: " + $scope.selectedOption);
        $scope.logentries.push(($scope.logentries.length + 1) + " - selection: " + $scope.selectedOption);
    });
});