DevT DevT - 3 months ago 10
AngularJS Question

AngularJS - Controller values not binding

In my MVC program simple angular value controllers values are not binding.
My code is as follows :

_Layout.cshtml

<body data-ng-app="ShoppingCartApp">
<div class="container body-content">
@RenderBody()
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/Scripts/angular.js")
@Scripts.Render("~/Scripts/Custom/App.js")
@Scripts.Render("~/Scripts/Custom/ShoppingCartController.js")
@RenderSection("scripts", required: false)
<hr />
</div>
</body>


App.js

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


ShoppingCartController.js

app.controller('ShoppingCartController', function ShoppingCartController($scope, $http) {
$scope.ShoppingCartObj.products = [];
$scope.test = "ABC";

// On load events
// $scope.loadValues();
});


My Html Code is follows :

@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}

<script></script>
<h2>Index</h2>
Total {{2+2}} // This value workd FINE
<div ng-controller="ShoppingCartController">
<div class="row">
<div class="nav navbar-nav navbar-left">
<h3>Total {{2+2}}</h3> // Not working THIS
</div>
<h1>{{test}}</h1> // Not working THIS

</div>
</div>


enter image description here

When i try to access value in controller or access directive inside controller it's not working. What i miss in here?

Answer

Change your controller to:

app.controller('ShoppingCartController', function($scope, $http) {....});

Or create a function named ShoppingCartController and then pass it to controller:

app.controller('ShoppingCartController', ShoppingCartController);