Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular.js Controller can't set properties

I'm using a clone of https://github.com/angular/angular-seed to make a simple Angular.js app. I'm trying to put in some properties to the controllers in order to bind them in my HTML but keep getting errors messages that I can't seem to figure out.

My controllers.js file looks like this currently:

'use strict';

/* Controllers */

angular.module('myApp.controllers', []).
  controller('MyCtrl1', [function($scope) {
    $scope.names = 'bob'
  }])
  .controller('MyCtrl2', [function() {

  }]); 

Here is the app.js too if it helps:

'use strict';

// Declare app level module which depends on filters, and services
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives',     'myApp.controllers']).
  config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/view1', {templateUrl: 'partials/partial1.html', controller:  'MyCtrl1'});
    $routeProvider.when('/view2', {templateUrl: 'partials/partial2.html', controller: 'MyCtrl2'});
    $routeProvider.otherwise({redirectTo: '/view1'});
  }]);

I've used the default name for the app "myApp" and have also called the ng-view within my HTML. When MyCtrl1 is in use I continually get this error:

TypeError: Cannot set property 'names' of undefined

Is there something syntactically wrong here? I've tried to only modify controllers.js to avoid having issues so there shouldn't be problems elsewhere...

like image 933
Shawn Taylor Avatar asked Apr 30 '13 20:04

Shawn Taylor


1 Answers

Controllers has a few overloads, you can either simplify your code to this:

angular.module('myApp.controllers', []).
  controller('MyCtrl1', function($scope) {
    $scope.names = 'bob'
  })
  .controller('MyCtrl2', function() {

  }); 

Or let Angular know what $scope is like this:

angular.module('myApp.controllers', []).
  controller('MyCtrl1', ['$scope', function($scope) {
    $scope.names = 'bob'
  }])
  .controller('MyCtrl2', [function() {

  }]); 

Reference: http://docs.angularjs.org/guide/dev_guide.mvc.understanding_controller

like image 117
Langdon Avatar answered Oct 20 '22 12:10

Langdon