0

I am attempting to learn angular.js and have seen a few different ways to initialize the module and controller.

here is how i found to do it through debugging one site I have been using as a guide.

var myApp = angular.module("myApp", []);
myApp.controller("myController", myController);

function myController($scope) {
     //some code
}

and her is a way I have seen it done on a few different tutorials

angular.moudule('myApp', []).controller('myController', function($scope){
    //some code
}

I understand that this may be a personal preference but I would like to know if there is a preferred way or a cleaner way to do it. Also if there is a better way to do please mention that as well.

2
  • 1
    This is the style guide I use: github.com/johnpapa/angular-styleguide Commented Jan 17, 2016 at 3:22
  • I like the guide I will read through it Commented Jan 17, 2016 at 3:35

3 Answers 3

1

Those two ways have more than one difference:

  • having a global var
  • chaining methods
  • inline callback function

That gives us eight total combinations from your two examples, which makes a direct comparison of each tedious. Use whatever you find the most readable to you (and your team) and appropriate for the project (for example, will you need that myApp variable elsewhere in the code such as for loading components from external files, etc). If you still can't decide, there are a couple of Angular style guides online, explore them.

Sign up to request clarification or add additional context in comments.

Comments

0

I do also follow john papa's style guide.. as per that you should define controllers as

/* recommended */

// some.controller.js
angular
    .module('app')
    .controller('SomeController', SomeController);

function SomeController() { }

Comments

0

There are many ways but always reusable one is better and helpful one.

Keeping module in a separate variable

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

myApp.controller('FirstController', ['$scope', function($scope) {
  $scope.greet = 'Hi Im First Controller !';
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="FirstController">
  {{ greet }}
</div>

Chaining the Method

var myApp = angular.module('myApp',[]).controller('SecondController', ['$scope', function($scope) {
      $scope.greet = 'Hi Im Chained Second Controller !';
    }]);
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <div ng-app="myApp" ng-controller="SecondController">
      {{ greet }}
    </div>

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.