Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it wrong to define controller in angular wrapped in a function?

I am looking at some code, and I see that it is written as shown below. It doesn't make sense to me. Is it wrong? Why is it written like that? Also, shouldn't the use strict; go at the very top, outside of the code?

(function() {
  'use strict';
  angular.module('itemList', [])
    .component('itemList', {
      templateUrl: 'item-list/item-list.component.html',
      controller: ['Item', ItemController]
  });

  function ItemController(Item) {
    //code
  }
}());
like image 264
user3152131 Avatar asked Jul 20 '16 12:07

user3152131


People also ask

What is the use of controller in angular?

AngularJS application mainly relies on controllers to control the flow of data in the application. A controller is defined using ng-controller directive. A controller is a JavaScript object that contains attributes/properties, and functions.

Are there controllers in angular?

AngularJS Controllers AngularJS applications are controlled by controllers. The ng-controller directive defines the application controller. A controller is a JavaScript Object, created by a standard JavaScript object constructor.

Can we inject one controller into another controller in AngularJS?

You can't inject controllers into one another.

What is the responsibility of the controller in AngularJS?

The primary responsibility of the controller is to create a scope object and thereby pass it to the view. With this, we come to an end of this AngularJS Controllers article.


1 Answers

The reason it is wrapped in an IIFE is to keep all declarations like "use strict", functions and variables local to the scope contained within and not set in global namespace

If "use strict" was set global it can affect other unrelated code that my not comply and thus would cause unexpected errors to be thrown

Is it wrong to define controller in...

No. It is a best practice

like image 98
charlietfl Avatar answered Nov 15 '22 09:11

charlietfl