2

I'm learning AngularJS and I have problem with data binding. When I try to get value from $scope.mytext i get {{mytext}}. Here is the code:

 <!DOCTYPE html>
 <html ng-app="myApp">
      <head>
    <title>Hello</title>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
</script>
    <script>
        var MainController = function ($scope) {
        $scope.mytext = "Angular JS Rulez";
        }
    </script>
</head>
<body>
<div ng-app> 
    <div ng-controller="MainController">
        <p>{{mytext}}</p>
    </div>
</div>
</body>
</html>`
2
  • Please make a better effort to format your code properly (including correct indentation). Commented Mar 20, 2016 at 0:14
  • 1
    @Knight did you try the code below? Commented Mar 20, 2016 at 0:51

2 Answers 2

1

You had some errors in the way you set up the app.

You never defined the app, you have declared ng-app twice, the second time you haven't assigned anything to ng-app and there was an error with the CDN you referenced. Once you defined the app, you then needed to assign the controller to this app.

The below code will work for you, and you can also see the code working by checking out this jsfiddle demo.

<!DOCTYPE html>
<html ng-app="myApp">
  <head>
     <title>Hello</title>
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>

     <script> 
          var myApp = angular.module('myApp',[]);
          myApp.controller('MainController', ['$scope', function($scope) {
               $scope.mytext = "Angular JS Rulez";;
          }]);
     </script>

  </head>
  <body>
     <div ng-controller="MainController">
        <p>{{mytext}}</p>
     </div>
 </body>
</html>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for help :)
1

Looks like you're calling the app in the html, but you haven't defined it anywhere. You must:

  1. define 'myApp' in the javascript portion, and then
  2. assign the controller on it.

Your code simply calls MainController which isn't defined properly on any app.

A basic setup in this case is, as Paul mentions:

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

myApp.controller(MyAppController, ['$scope', function($scope) {
   ...add $scope elements here ... 
]);

Also you shouldn't need to call ng-app twice in the html.

Comments

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.