HTML SELECT element with angular data-binding

The Angular js ng-options directive supports the following the possible options

for array data sources:

  • label for value in array
  • select as label for value in array
  • label group by group for value in array
  • select as label group by group for value in array

for object data sources:

  • label for (key , value) in object
  • select as label for (key , value) in object
  • label group by group for (key, value) in object
  • select as label group by group for (key, value) in obj

The following simple JSFiddle shall helps you in understanding the usage of the above.

Javascript

function ControllerA($scope) {
    $scope.optionsArray = [1,2,3,4,5];
    $scope.optionsObject = {"India" : "IN" , "Singapore" : "SG", "Malaysia" : "MY"};
    $scope.optionsGroup = [
        { "country" : "India" , "city" : "Chennai"}, 
        { "country" : "India" , "city" : "Mumbai"},
        { "country" : "India" , "city" : "Delhi"},
        { "country" : "India" , "city" : "Calcutta"},
        { "country" : "Singapore" , "city" : "Singapore"}
    ];

}​

HTML

<div ng-controller="ControllerA" ng-app>
    Simple Array as options<br/>
    <select ng-options="value for value in optionsArray" ng-model="chosenA">
</select><br/>
    chosenA = {{chosenA}}<br/>
    <hr/>



    Simple options<br/>
    <select ng-options="value for (key, value) in optionsObject " ng-model="chosenO">
</select><br/>
    chosenO = {{chosenO}}<br/>
    <hr/>    



    Simple Object with key as value<br/>
    <select ng-options="value as key for (key, value) in optionsObject " ng-model="chosenO1">
</select><br/>
    chosenO1 = {{chosenO1}}<br/>
    <hr/>    


    Options Group<br/>
    <select ng-options="value.city group by value.country for value in optionsGroup" ng-model="chosenO2">
</select><br/>
    chosenO2 = {{chosenO2}}<br/>
    <hr/>        
</div>

JsFiddle

http://jsfiddle.net/ramandv/zFtkR/

Posted in AngularJS, Javascript | 3 Comments

Angular JS : Sharing data

In many scenarios, the data needs to be shared between different scopes. There are different ways to share the data among the scopes. The proper one can be chosen based on the need.

1. Sharing data between Parent scope and Child scope

If Parent-Child relationship can be established, then the data sharing can be implemented as follows.

In AngularJS, Scopes inherits prototypically. ie. In simple terms, if the property is not defined in the child scope, it will be accessed from the parent’s scope. The parent scope’s member variable can be accessed by “$scope.$parent” property from child’s scope.

Javascript

function Parent($scope) {
    $scope.x= 5;
    $scope.y= 5;
}

function Child($scope) {
    $scope.modifyBothScopes= function() {
       $scope.$parent.x++;
    };
    $scope.modifyonlyChildscope= function() {
       // member "y" will be created in the child scope
       // So, after the following statment,  $scope.$parent.y++  will only increment the parent scope. 
       // It would not affect the child scope.
       $scope.y++;
    };

}

Html

<div ng-controller="Parent">
    parentX = {{x}} <br/>
    parentY = {{y}}<br/>
<div ng-controller="Child">
    childX = {{x}}<br/>
    childY = {{y}}<br/>
    <a ng-click="modifyBothScopes()">modifyBothScopes</a><br>
    <a ng-click="modifyonlyChildscope()">modifyonlyChildscope</a>
</div>
</div>​

JS Fiddle

http://jsfiddle.net/ramandv/JHwxP/

2. Sharing data using Service [like a global variable]

To share the data among independent controllers, Services can be used. Create a service with the data model that needs to be shared. Inject the service in the respective controllers.

In the following example, Service is used to store the variable x. The independent controllers will check the value of X whenever needed.

Javascript

angular.module('myApp', [])
    .service('myService', function () {
        var x=5 ;
        return {
            increase : function() {
                x++;
            },
            getX : function() {
                return x;
            }
       };
    })

function ControllerA($scope, myService) {
    $scope.x = 1;
    $scope.incrementDataInService= function() {
        myService.increase();
    }
    $scope.syncDataWithService= function() {
        $scope.x = myService.getX();
    }        
}

function ControllerB($scope, myService) {
   $scope.x = 1;
    $scope.incrementDataInService= function() {
        myService.increase();            
    }
    $scope.syncDataWithService= function() {
        $scope.x = myService.getX();
    }    
}​
​

HTML

<div ng-app="myApp">
    <div ng-controller="ControllerA">
        ControllerA.X = {{x}}<br/>
        <a ng-click="incrementDataInService()">incrementDataInService</a><br>     
        <a ng-click="syncDataWithService()">syncDataWithService</a><br>           
    </div>
    <hr/>
    <div ng-controller="ControllerB">
        ControllerB.X = {{x}}<br/>
        <a ng-click="incrementDataInService()">incrementDataInService</a><br>     
        <a ng-click="syncDataWithService()">syncDataWithService</a><br>   
    </div>
</div>
​​

JS Fiddle

http://jsfiddle.net/ramandv/kR859/

3. Sharing data using Service – monitor the changes

In some times, it is important to monitor the changes in the service. AngularJS provides “$broadcast” to broadcast the data to the listening subscribers.

The following contrived example shows the usage of $broadcast. The ControllerA and ControllerB subscribed to the event “XChanged”. The service “myService” will broadcast the event “XChanged” when the value of “x” changes.

Javascript

angular.module('myApp', [])
    .service('myService',  function ($rootScope) {
        var x=5 ;
        return {
            increase : function() {
                x++;
                $rootScope.$broadcast('XChanged', x);
            }
       };
    })

function ControllerA($scope, myService) {
    $scope.x = 1;
    $scope.incrementDataInService= function() {
        myService.increase();
    }     
    $scope.$on('XChanged', function(event, x) {
        $scope.x = x;
    });        
}

function ControllerB($scope, myService) {
   $scope.x = 1;
    $scope.incrementDataInService= function() {
        myService.increase();            
    }
    $scope.$on('XChanged', function(event, x) {
        $scope.x = x;
    });           
}​
​

HTML

<div ng-app="myApp">
    <div ng-controller="ControllerA">
        ControllerA.X = {{x}}<br/>
        <a ng-click="incrementDataInService()">incrementDataInService</a><br>     
    </div>
    <hr/>
    <div ng-controller="ControllerB">
        ControllerB.X = {{x}}<br/>
        <a ng-click="incrementDataInService()">incrementDataInService</a><br>     
     </div>
</div>

JS Fiddle

http://jsfiddle.net/ramandv/25CVc/

Posted in AngularJS, Javascript | 17 Comments

Using Google maps with AngularJS and Angular UI

You can use AngularUI to integrate Google Maps in your angularjs app. The following code snippet shows a simple example of Google maps with Angular UI.

To hookup the events with map elements such as marker, polyline, you need to create html div elements with existing Google maps objects. It is a bit confusing part, but it helps to keep your controller free from adding listener codes.

//Add the requried module 'angular-ui' as a dependency
angular.module('maptesting', ['ui']);

function MapCtrl($scope) {
    var ll = new google.maps.LatLng(13.0810, 80.2740);
    $scope.mapOptions = {
        center: ll,
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    //Markers should be added after map is loaded
    $scope.onMapIdle = function() {
        if ($scope.myMarkers === undefined){
            var marker = new google.maps.Marker({
                map: $scope.myMap,
                position: ll
            });
            $scope.myMarkers = [marker, ];
        }
    };

    $scope.markerClicked = function(m) {
        window.alert("clicked");
    };

}​

<div ng-app='maptesting'>
    <div ng-controller="MapCtrl">
        <div id="map_canvas" ui-map="myMap" 
      style="height:300px;width:400px;border:2px solid #777777;margin:3px; border:1px solid" 
      ui-options="mapOptions" 
      ui-event="{'map-idle' : 'onMapIdle()'}"
      >
        </div>

        <!--In addition to creating the markers on the map, 
       div elements with existing google.maps.Marker object 
        should be created to hook up with events -->
        <div ng-repeat="marker in myMarkers" ui-map-marker="myMarkers[$index]"
                      ui-event="{'map-click': 'markerClicked(marker)'}">
        </div>
    </div>
</div>

JS Fiddle

http://jsfiddle.net/ramandv/xSPAA/

Posted in AngularJS, Javascript | 18 Comments