0

I am new to Angularjs so i made one example to call a controller but i am not able to call controller ...

this is my sample code

<head>

    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript" src="js/jquery-1.9.0.js"></script>
    <script type="text/javascript" src="angularjs/angular.min.js"></script>
</head>

<body ng-app="">
    <div data-ng-controller="mycontroller">
    </div>
    <script>
        function mycontroller($scope, $http) {
            alert("alert");
        }
    </script>
</body>
5
  • 1
    You need to use ng-app to initialise the whole app Commented Apr 1, 2015 at 13:37
  • Start with this seed project google.com.au/… Commented Apr 1, 2015 at 13:38
  • @in_visible it's already used on the body tag Commented Apr 1, 2015 at 13:38
  • You are missing the main module also, which is reference by ng-app directive. Commented Apr 1, 2015 at 13:39
  • @Khalid it was not before, the question has been edited. Commented Apr 1, 2015 at 13:39

2 Answers 2

3

try this

<body ng-app="learning">
    <div data-ng-controller="mycontroller">
    </div>
    <script>
        angular.module("learning", [])
            .controller("mycontroller", function($scope, $http) {
                alert("alert");
            });
    </script>
</body>
Sign up to request clarification or add additional context in comments.

2 Comments

but i want to do with this .is any wrong in this code
in your code (1) ng-app="" does not have any name & (2) global function as controller is deprecated from angular1.3
1

You can try this, but I recommend you to read angular tutorials to understand how controllers and binds works.

http://www.w3schools.com/angular/ https://docs.angularjs.org/tutorial

<html>
<head>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>

<div ng-app="myApp"> 
    <div ng-controller="mycontroller" ng-init="initMethod()">
        <!--<input type="text" ng-model="test"></p>
        <div>{{test}}</div>-->
    </div>
</div>
<script>
    var app = angular.module('myApp', []);
    app.controller('mycontroller', function($scope) {
        alert("alert")

        $scope.initMethod = function(){
            alert("alert from init");
        }
    });
</script>
</body>
</html>

2 Comments

ya it's good but i want to know that what mistake am i doing ?
You need declare a app (ng-app binding) in the document and then add the controller to the app. For ng-init binding is just a alternative to initialize your code instead of write directly in the controller

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.