7

次の場合、コンソールに「ReferenceError:ThingCtrlisnotdefined」というエラーが返されます。

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

myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
    when('/things', {templateUrl: 'partial.html', controller: ThingCtrl}).
    when('/things/:id', {templateUrl: 'detail.html', controller: ThingCtrl}).
otherwise({redirectTo: '/things'});
 }]);

myApp.controller('ThingCtrl', ['$scope', '$routeParams', function($scope, $routeParams) {
$scope.thing = [
    {
        'title':'first thing',
        'first':'one',
        'second': 'two',
        'third': 'three'
    }
];

}]);

ただし、コントローラーが次のように定義されている場合は正常に機能します。

function ThingCtrl($scope, $routeParams) {
        $scope.thing = [
    {
        'title':'first thing',
        'first':'one',
        'second': 'two',
        'third': 'three'
    }
  ]
};

モジュラー構文を使用して機能しないのはなぜですか?

4

1 に答える 1

11

問題はここにあると思います:

when('/things', {templateUrl: 'partial.html', controller: ThingCtrl})

これは、未定義でエラーの原因となるThingCtrlオブジェクトを指すようにAngularに指示しています。

コントローラ名を次のように引用符で囲んでみてください。

when('/things', {templateUrl: 'partial.html', controller: 'ThingCtrl'})

これにより、Angularが依存性注入を適切に使用できるようになります。

于 2013-01-28T15:40:58.473 に答える