Using application name in angular js div does not work

Here is my html and angular js code

<html> <head> <title></title> <script src="Scripts/angular.min.js" type="text/javascript"></script> <script type="text/javascript" language="javascript"> function DemoController($scope) { $scope.user = { dateOfBirth: new Date(1970, 0, 1) } } </script> </head> <body> <div ng-app="demo" ng-controller="DemoController"> Date Of Birth: <my-datepicker type="text" ng-model="user.dateOfBirth" /> <br> Current user date of birth: <span id="dateOfBirthDisplay">{{user.dateOfBirth}}</span> </div> </body> </html> 

It does not work and gives a conclusion

  Date Of Birth: Current user date of birth: {{user.dateOfBirth}} 

But if I remove ="demo" from ng-app="demo" in the div, it works ...

+4
source share
3 answers

When you assign a name to the ng-app directive, you essentially create a module with that name. In this module you will need to define your directives, services, filters and configurations.

In your case, when you assigned the name "demo", you created a module named "demo". The DemoController function DemoController now no longer part of this module.

To use this function AND assign a module to your application, you need to use the following method for defining a controller:

 var app = angular.module("demo", []); app.controller('DemoController', [function () { //The body of demo controller }]); 

Thus, the application knows which module controller needs to be bound for the corresponding view area.

EDIT: Link to ng-app directive

+7
source

My solution works, try the following: http://plnkr.co/edit/zwOKitT8wznO17yZfz15?p=preview

 <body ng-app=""> <div ng-controller="DemoController"> Date Of Birth: <br> Current user date of birth: <span id="dateOfBirthDisplay"><span ng-bind="user.dateOfBirth"></span></span> </div> </body> 
+1
source

The value of the ng-app attribute defines the application module name. In your case, this is a "demo". Until you declare a DemoController in the demo module using the angular.module call, it does not appear inside your ng-app html, executed as part of the demo module.

What will work for ng-app="demo" :

 <script type="text/javascript" language="javascript"> angular.module('demo', []).controller('DemoController', function ($scope) { $scope.user = { dateOfBirth: new Date(1970, 0, 1) } }); </script> 
0
source

Source: https://habr.com/ru/post/1488422/


All Articles