ankur ankur - 1 month ago 22x
AngularJS Question

How to pass url from view to Angularjs Controller file?

I am passing url from view to controller for


View( MVC View)

<form name="form" ng-controller="LoginController" >
<div id="dvContainer" ng-init="Url= @Url.Action("VerifyLogin", "Visitor")">
<span ng-model="Message" class="text-danger"></span>
<input name="txtUser" type="text" required ng-model="UserName" />
<span ng-show="(form.txtUser.$dirty || submitted) &&
form.txtUser.$error.required">UserName is required.</span>
<td><input type="password" required ng-model="Password" /></td>
<td colspan="2"><button type="submit" ng-click="submit($event)">Login</button></td>


In my Controller(Angularjs Controller)

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

//AngularJS controller
app.controller('LoginController', function ($scope, $http) {
$scope.submit = function () {
// Set the 'submitted' flag to true
var loginModel = {
UserName: $scope.UserName,

$$scope.Url, loginModel).success(function (data) {
$scope.Message = data.Message;
}).error(function (data) {
$scope.error = "An error has occured while adding! " + data;

I am trying to access Url that is being defined using ng-init . The application is throwing error

[$parse:syntax] Syntax Error: Token '/' not a primary expression at column 6 of the expression [Url= /Visitor/VerifyLogin] starting at [/Visitor/VerifyLogin].

I am pretty new to Angularjs so Could not figure out what is that i am doing wrong.


You can use the angular value provider to pass this url ( or any other stuff)from your view to your angular controller.

Just create a javascript object and create a Url property and set the value of this and use the value provider to pass this object.

@section Scripts
   <script src="~/Scripts/YourAngularControllerFileForThisPage.js"></script>
        var myApp = myApp || {};
        myApp.Settings = myApp.Settings || {};
        myApp.Settings.Url= "@Url.Action("VerifyLogin","Visitor")";
        angular.module("app").value("appSettings", myApp);

Now in your controller, simply use the appSettings object

var app = angular.module("app", []);
app.controller('ctrl', ['$scope', 'appSettings', function ($scope, appSettings) {
    $scope.URL = 'nothing';
    $scope.greeting = 'Hola!';
    console.log('Url  ', appSettings.Settings.Url);
    // You can use appSettings.Settings.Url for your ajax calls now