Angular-js

How can I pass parameter to an angularJS controller in asp.Net MVC?

How can I pass parameter to an angularJS controller in asp.Net MVC?, someone asked me to explain?

In this article I will show you to pass parameter to an angularJS controller using angularJS method ng-init. If the user passes the value via ng-init into an html page and you will get the parameter from the scope object of angularJS controller.

MVC View:

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>
<script src="~/Scripts/app.js"></script>
 <div data-ng-app="myModule">
  <div data-ng-controller="myController" data-ng-init="init(@Model.UserId)">
   <h2>Name of the employee is {{name}}</h2>
  </div>
</
div>

AngularJS app.js:

 

angular.module('myModule', []);
function myController($compile, $scope, $http) {
        //Thisfunction is sort of private constructor for controller
    $scope.init = function (id) {
        $scope.myInterval = 5000;
        $scope.name = null;
        $scope.UserId = id;
        $http({
            method: 'Get',
            url: '/Home/GetData',
            params: {
                UserId: $scope.UserId
            },
        }).success(function (data, status,headers, config) {
            $scope.name = data;
        }).error(function (data, status, headers, config) {
            $scope.message = 'Unexpected Error';
       });
    }

MVC Controller:

public JsonResult GetData(int UserId)
        {
            using (models context = new models())
            {
                var ret = context.Users.Where(s => s.UserId == UserId).ToList().Select(x=> new { x.UserId,x.Name }).ToList();
                return Json(ret, JsonRequestBehavior.AllowGet);
            }
        }

The MVC controller receives the parameter UserId and filters the record from the Collection (Users) and return as JSON string and bind to the html element.

 

Output:

pass paremeter using angularjs method ng-init

Post your comments / questions