0

I'm a newbie to this thing called 'AngularJS' so I got stuck at one point.

Consider the below code sample :

<!DOCTYPE html>
<html>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  <body>
    <div ng-app="" ng-init="firstName='John'">
      <p>Input something in the input box:</p>
      <p>Name: <input type="text" ng-bind="firstName"></p>
      <p>You wrote: {{ firstName }}</p>
    </div>
  </body>
</html>

In above example why can't I bind the value of application variable "firstName" to the HTML input text control usng "ng-bind"?

and suppose I write the code as below :

<!DOCTYPE html>
<html>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  <body>
    <div ng-app="" ng-init="firstName='John'">
      <p>Input something in the input box:</p>
      <p>Name: <input type="text" ng-model="firstName"></p>
      <p>You wrote: {{ firstName }}</p>
    </div>
  </body>
</html>

In above example I can bind the value of application variable "firstName" to the HTML input conrol using "ng-model".

Can someone please clarify me the difference between the above two codes in easy to understand language?

Also, look at below code snippet :

<!DOCTYPE html>
<html>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  <body>
    <div ng-app="" ng-init="firstName='John'">
      <p>The name is <span ng-bind="firstName"></span></p>
    </div>
  </body>
</html>

In the above(third) example how could I be able to bind the value of application variable "firstName" to the <p> tag?

Someone please explain me.

Thanks.

PHPLover
  • 1
  • 51
  • 158
  • 311

1 Answers1

0

ng-bind makes a one way binding between your controller and the view. In this case, the view will only reflect changes made in the controller, but not viceversa. This is the same as using the double brackets notation {{variable}}

In the other hand, ng-model makes a double binding, that is, changes made in the view (normally in an input form), will be accesible automatically in the controller, and changes made in the controller will be updated in the view

check this answer: https://stackoverflow.com/a/12420157/5186787

In regard to the snippet, you could just do:

    <!DOCTYPE html>
    <html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
      <body>
        <div ng-app="myApp" ng-controller='myController'>
          <p>{{firstName}}</p>
        </div>
      </body>
    </html>

Which implements a one way bind. So, if you have your application defined in this way:

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

    app.controller('myController', ['$scope',function($scope){
      $scope.firstName = 'John Doe';
    }]);

It would make a one-way binding between your variable firstName in the controller and the view.

It is better to use controllers for this type of work.

Community
  • 1
  • 1