1

im new to AngularJS and im having trouble creating a controller for my page

  1. its a simple page that load app.js file that has $scope.name = "james"; and i use the expression {{ $scope.name }} to display that value which isnt coming up.. but when i run {{ 2 + 4 }} it shows 6 so angular is working..

  2. another thing is when i open the page in safari the expressions are being displayed raw (meaning : '{{ 2 + 4 }}') but chrome would run it and will show the results..

here is my code.. thanks for helping

HTML
        <!DOCTYPE html>
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script> 
        <script src="app.js"></script>

        <meta charset="utf-8">

        <title></title>
    </head>

    <body>

    <div data-ng-app="myApp" data-ng-controller="myCtrl">
        {{  $scope.name }}
        {{  2 + 4 }}


        </div>


    </body>
    </html>

app.js

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

myApp.controller('myCtrl', function($scope){

   $scope.name = "James"
})

2 Answers 2

1

seems to be working ok for me here is a plunkr. https://plnkr.co/edit/uXqvoIrgNjEZq8cHRE3Z?p=preview

I am using the angular style guide. https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md

<script src="https://code.angularjs.org/1.5.5/angular.js"></script>
<script src="./script.js"></script>
<div ng-app="myApp">
    <div ng-controller="myCtrl as vm">
       {{  vm.name }}
        {{  2 + 4 }}
    </div> 
</div>

(function() {
    'use strict';
angular
  .module('myApp', [])
  .controller('myCtrl', myCtrl);

   function myCtrl(){
       /* jshint validthis: true */
       var vm=this;
       vm.name = "James";
   } 

})();
Sign up to request clarification or add additional context in comments.

1 Comment

This is the correct answer as it's recommended to use controllerAs w/ AngularJS controllers.
1

your issue here is that you are misunderstanding how $scope works.

$scope is a special object provided by AngularJs which allows you to add properties to it, which AngularJs will attach Watchers to, for Two Way Binding. In your HTML expressions ({{ }}), you don't refer to the $scope, you refer to the property of $scope that you are interested in.

In other words, instead of {{ $scope.name }}, you should use simply {{ name }}.

Note that there are many style guides which will suggest alternatives to using $scope, but the most important aspect of $scope in more advanced situations is to always use a dot in your bindings, if possible.

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.