Search code examples
javascripthtmlangularjsinspect-element

Angular JS from tutorial not rendering


I just got a book on Angular JS. I'm setting up the first project, which is very simple. There is just one Angular element to be rendered. I'd like to get this set up properly from the beginning, so I want to overcome this simple problem now. The angular.js file and app.js file are in the same folder that index.html is in, for simplicity. I downloaded the newest version of angular (1.3.2), and tried using the minimized .js file before trying this with the uncompressed. This code is copy-pasted from the book I'm using, which was published in 2013.

index.html:

<html ng-app>
    <head>
        <script src="angular.js"></script>
        <script src="app.js"></script>
    </head>
    <body>
        <div ng-controller='HelloController'>
            <p>{{greeting.text}}, World</p>
        </div>
    </body>
</html>

app.js:

function HelloController($scope) {
    $scope.greeting = { text: 'Hello' };
}

When index.html is opened in my browser (the latest version of Chrome), the "{{greeting.text}}" area is displayed as that string, {{greeting.text}}, not the value of the variable. When I open the dev tools, I see that there's been an error on the controller, with it not being defined as a controller. I know this is pretty simple stuff, but I want to have all my declarations right from the beginning so that I can learn Angular. Any help would be appreciated.


Solution

  • Update

    Agree with @JaredReeves , so do declarr module variable like this

    //module file 
    angular.module('yourAppDep');
    
    // Controller One File
        angular.module('yourAppDep').controller('MyCtrl', function () {
          // ...
    });
    

    Create module for you application like this, in module.js file

    var AngularMVCApp = angular.module('AngularMVCApp', []);
    
    AngularMVCApp.controller('HelloController', HelloController);
    

    change you html like as below

    <html ng-app="AngularMVCApp">
    

    change you controller like this

    function HelloController($scope) {
        $scope.greeting = { text: 'Hello' };
    }
    
    // The $inject property of every controller (and pretty much every other type of 
     //object in Angular) needs to be a 
     //string array equal to the controllers arguments, only as strings
     HelloController.$inject = ['$scope'];
    

    You can also check basic tutorial here : http://www.codeproject.com/Articles/806029/Getting-started-with-AngularJS-and-ASP-NET-MVC-Par