ui.router, $scope, and controllerAs

2019-07-28 20:01发布

I am unable to get the following to work, I keep getting an Unknown provider error. Any ideas?

var app = angular.module('app', ['ui.router']);

app.config(function($stateProvider, $urlRouterProvider) {

    $urlRouterProvider.otherwise("/");

    $stateProvider
        .state("home", {
            url : "/",
            templateUrl : "resources/static/views/home.html",
            controller: "HomeCtrl",
            controllerAs: "homeCtrl"
        }
    );
});

app.controller("HomeCtrl", ["$scope", function ($scope) {

    var _this = this;

    // do stuff

}]);

Full Error:

angular.1.5.8.min.js:118 Error: [$injector:unpr] http://errors.angularjs.org/1.5.8/$injector/unpr?p0=<div ui-view="" class="ng-scope">copeProvider%20%3C-%20%24scope%20%3C-%20HomeCtrl
    at Error (native)
    at http://localhost:8080/resources/scripts/js/include/angular.1.5.8.min.js:6:412
    at http://localhost:8080/resources/scripts/js/include/angular.1.5.8.min.js:43:174
    at Object.d [as get] (http://localhost:8080/resources/scripts/js/include/angular.1.5.8.min.js:40:432)
    at http://localhost:8080/resources/scripts/js/include/angular.1.5.8.min.js:43:236
    at d (http://localhost:8080/resources/scripts/js/include/angular.1.5.8.min.js:40:432)
    at e (http://localhost:8080/resources/scripts/js/include/angular.1.5.8.min.js:41:158)
    at Object.instantiate (http://localhost:8080/resources/scripts/js/include/angular.1.5.8.min.js:42:24)
    at http://localhost:8080/resources/scripts/js/include/angular.1.5.8.min.js:90:32
    at Object.<anonymous> (http://localhost:8080/resources/scripts/js/include/angular-ui-router.0.3.1.min.js:7:23872)

And link

And html

<div>Home</div>

For clarity, I need to use controllerAs, so removing it is not an option.

EDIT: Must be a bug in version 0.3.1 of ui.router, when I switched to 0.3.2 it worked fine.

1条回答
Ridiculous、
2楼-- · 2019-07-28 20:39

You are missing data-ui-view in index.html,

<body data-ng-app="myApp">
  <h2>AngularJS Ui router - Demonstration</h2>
  <div data-ui-view=""></div>
</body>

Controller:

var myApp = angular.module("myApp", ['ui.router']);
myApp.config(function($stateProvider, $urlRouterProvider) {
  $urlRouterProvider.when("", "/home");
  $stateProvider
    .state("home", {
      url: "/home",
      templateUrl: "home.html",
      controller: 'HomeCtrl',
      controllerAs: "home"
    });
});
myApp.controller('HomeCtrl', ['$scope', function($scope) {
    var vm = this;
     vm.hello = "DEMO";

}]);

DEMO

查看更多
登录 后发表回答