1

I'm getting this error,

Argument 'ctrl1' is not a function, got undefined

on running the latest angularjs v1.3.15. Should my syntax be any different here?

This is the html

<body ng-app="app">

  <div ng-controller="ctrl1">

      {{color}}

      {{root_color}}

  </div>

  <div ng-controller="ctrl2">

      {{color}}

      {{root_color}}

  </div>

  </body>

And this is the angularjs code

   angular.module('app', []).controller('ctrl1', ['$scope', function ctrl1($scope){

    $scope.color = "yellow";
    $scope.root_color = "red";

   }]);



   angular.module('app', []).controller('ctrl2', ['$scope', function ctrl2($scope){

    $scope.color = "yellow";
    $scope.root_color = "red";

   }]);
2
  • 4
    Doesn't the second line redefine the app module, thus blowing away the definition of ctrl1? Commented Mar 22, 2015 at 13:15
  • 1
    While not the cause of the problem, there is no need to put a name before function. Change 'function ctrl2' to just 'function'. Save a few bytes of typing. Commented Mar 22, 2015 at 13:28

2 Answers 2

2

You're overriding the first controller with the 2nd. Use

var app=angular.module('app', []);
//1st controller
app.controller('ctrl1', function ctrl1($scope){

$scope.color = "yellow";
$scope.root_color = "red";

});
//2nd controller
app.controller('ctrl2', function ctrl2($scope){

$scope.color = "yellow";
$scope.root_color = "red";

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

Comments

1

You are defining controller ctrl1 in you app then again redefining same app with ctrl2, which was flushing initially defined controller ctrl1.

And on angular side while ng-controller directive gets compiled it doesn't get controller with name ctrl1, so second time while registering second controller you should use only module name like angular.module('app') instead of angular.module('app', [])

Code

angular.module('app', []).controller('ctrl1', ['$scope',
    function ctrl1($scope) {
        $scope.color = "yellow";
        $scope.root_color = "red";
    }
]);

angular.module('app').controller('ctrl2', ['$scope',
    function ctrl2($scope) {
        $scope.color = "yellow";
        $scope.root_color = "red";
    }
]);

Hope this could help you, Thanks.

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.