user3427540
user3427540

Reputation: 1172

Does $scope is automatically injected to controller in Angular js?

Initially I was thinking $scope is automatically injected to controller in Angular JS.But Now I am confused. I wrote a small snippet of code.

index.html

 <html ng-app>
  <body ng-controller="Controller">
  <input type="text" ng-model="fname">
  <span ng-bind="fname"></span>
 <body>
</html>

script.js

angular.module('docsSimpleDirective', [])
.controller('Controller', ['$http', function($scope) {
    $scope.fname = 'Foo Bar';

}])

As you can see I am not injecting $scope here to the controller. When the page loads, it does not show 'Foo Bar' on the textfield or span. But when I start writing some value on the text field , It reflects on the span. This means 'fname' declared in scope.But why its not showing on the page load. Everything works fine when I inject $scope.

Upvotes: 2

Views: 223

Answers (1)

Malkus
Malkus

Reputation: 3726

You have a couple different things going on.

First, you need to bind the app in some way to the DOM, in this case you named your module docsSimpleDirective so you need to add ng-app="docsSimpleDirective a the same level or above your controllers

<!-- added ng-app="docsSimpleDirective" -->
<div ng-app="docsSimpleDirective" ng-controller="Controller">
  <input type="text" ng-model="fname">
  <span ng-bind="fname"></span>
</div>

Second, you are using the array annotation for defining dependencies which is good. You will run into problems if you don't do this and you try to uglify your code. The way you currently have it bound you do not pass $scope to the controller you are passing $http with the name $scope.

angular.module('docsSimpleDirective', [])
.controller('Controller', ['$scope', function($scope) { 
          // Not ['$http', function($scope)....
    $scope.fname = 'Foo Bar';
}])

If you want to pass $scope and $http to the controller it would be defined like this.

.controller('Controller', ['$scope','$http', function($scope,$http) { 

In short you could do .controller('Controller', ['$scope','$http', function(foo,bar) { ... and foo would equal $scopeand bar would equal $http. This is done so that when the code is uglified and uglifiery will not change the literal strings for $scope and $http so the references will not be broken.

Here is a working Fiddle

Upvotes: 3

Related Questions