简体   繁体   中英

AngularJS + ASP.NET MVC - Controller undefined

Hullo everyone, I am having a problem with AngularJs not reconizing my controller, I have summarised what I have done below.

Starting point: AngularJs tutorial http://www.thinkster.io/angularjs/ZPCQtVfGba/angularjs-controllers

Problem: defined controller in file (gets retrieved correctly when visiting page), added ng-controller directive to relevant div, got javascript runtime error (

Error: [ng:areq] http://errors.angularjs.org/1.3.0-beta.18/ng/areq?p0=FirstCtrl&p1=not%20a%20function%2C%20got%20undefined

)

Before posting I checked whether I had included my controller implementation before including Angular but it is not the case.

What am I missing? I suspect it might have something to do with declaring controllers in the global scope (eg Controller not a function, got undefined, while defining controllers globally ) but I am not really sure whether this is indeed the case.

Thanks in advance!

_Layout .cshtml

<!DOCTYPE html>
<html ng-app>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @RenderSection("PageSpecificStyles",required:false)
</head>
<body>

    @RenderBody()


    @RenderSection("BodyScripts", required: false)
</body>
</html>

Index.cshtml:

@{
    ViewBag.Title = "Home Page";
}

@section PageSpecificStyles{
    <style>
        div {
            margin-left: 20%;
        }
    </style>
}

@section BodyScripts{
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.18/angular.min.js"></script>
    <script src="~/Scripts/FirstCtrl.js"></script>
}
<div ng-controller="FirstCtrl">

    <div>
        <h1>Hello {{data.message}}</h1>
    </div>
</div>

FirstCtrl.js (in ~/scripts)

function FirstCtrl($scope) {
    $scope.data = { message: "Cat!" };
}

As you suspected, since you are using angular 1.3 beta which has no implicit support for Global controller constructor function discovery , you need to register your controller with the module.

   angular.module('yourApp').controller('FirstCtrl',['$scope', FirstCtrl]);

and also since you are defining an module you need to specify the module name in your ng-app.

  <html ng-app="yourApp">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM