Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

AngularJS ui router custom data

Suggested Videos
Part 45 - AngularJS ui router optional parameters
Part 46 - Case sensitivity with angularjs ui-router
Part 47 - Angular ui router default route



In this video we will discuss how to add custom data to a state in angular.



To add custom data to a state use data property. In the example below, we have added a "data" a property to the "home" state. The value for this property is a Javascript object that contains our custom data. Along the same lines we have added custom data to the "courses" state.

$stateProvider
    .state("home", {
        url:"/home",
        templateUrl: "Templates/home.html",
        controller: "homeController",
        controllerAs: "homeCtrl",
        data: {
            customData1: "Home State Custom Data 1",
            customData2: "Home State Custom Data 2"
        }
    })
    .state("courses", {
        url:"/courses",
        templateUrl: "Templates/courses.html",
        controller: "coursesController",
        controllerAs: "coursesCtrl",
        data: {
            customData1: "Courses State Custom Data 1",
            customData2: "Courses State Custom Data 2"
        }
    })

The custom data is now available in all the controllers. To access state custom data from it's controller (i.e to access home state data from home controller) use $state.current.data.customPropertyName. To access state custom data from a different controller (i.e to access courses state data from home controller) use $state.get("statename").data.customPropertyName

.controller("homeController", function ($state) {
    this.message = "Home Page";

    this.homeCustomData1 = $state.current.data.customData1;
    this.homeCustomData2 = $state.current.data.customData2;

    this.coursesCustomData1 = $state.get("courses").data.customData1;
    this.coursesCustomData2 = $state.get("courses").data.customData2;
})

Modify home.html as shown below, if you want to display the custom data on the home view

<fieldset>
    <legend>Home</legend>
    Custom Data 1 : {{homeCtrl.homeCustomData1}}
    <br />
    Custom Data 2 : {{homeCtrl.homeCustomData2}}
</fieldset>

<fieldset>
    <legend>Courses</legend>
    Custom Data 1 : {{homeCtrl.coursesCustomData1}}
    <br />
    Custom Data 2 : {{homeCtrl.coursesCustomData2}}
</fieldset>

With all the above changes, the custom data will be displayed on the home view as shown below.

AngularJS ui router custom data

AngularJS tutorial for beginners

No comments:

Post a Comment

If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.