1

I'm new to AngularJs and I try to understand the basics of controller binding. lets say I have this in my html page:

<div ng-controller ="MainController">
            <h2>{{message}}</h2>
        </div>

Now, in my script file I have two options(as I saw in different tutorials):

1:

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

myApp.controller('MainController', ['$scope', function($scope) {
  $scope.message = 'hello';
}]);

2:

var MainController = function($scope)
{
    @scope.message = "Hello";
};

Offcourse I prefer the second approach however only the first option works for me. I'm working with AngularJS 1.4.4, could it be the second approach is now deprecated?

Thanks!

1 Answer 1

1

The second approach is just assigning the controller code to a variable, where in your first approach you pass it directly into the controller function. To make the second approach work, you'd have to pass that variable into the controller function as follows.

myApp.controller('MainController', MainController);

You're doing the same thing. I go with the second approach because I think it's cleaner. Check out John Papa's style guide for clean guidelines on how to write your Angular code.

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

2 Comments

Hi, I'm watching a pluralsight video which doesn't use the line you wrote.
Hm, well AFAIK, you can't just define a function with the word "Controller" in it and expect it to work properly. Hard for me to say without seeing any of the video or source code though.

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.