从另一个模块注入服务使ui路由器工作失败

时间:2019-01-17 07:40:58

标签: angularjs angular-ui-router

我正在使用angular-ui-router在我的应用程序的一个模块(用AngularJS编写)中实现路由。我的模块正在使用其他模块的服务,因此在Controller中我注入了它们。 现在,当我使用注入其他模块的组件后,路由不起作用。如果删除引用,它可以正常工作。 我将在下面显示MWE。

我尝试将ui.router注入其他模块,但是没有用。 我发现的唯一解决方案是将服务移至我的模块。我想避免这种方法。

index.html

<html>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.21/angular-ui-router.js"></script>
  <script src="helloworld.js"></script>
  <script src="component.js"></script>
  <script src="service.js"></script>
</head>

<body ng-app="foo">
  <a ui-sref="hello" ui-sref-active="active">Hello</a>
  <ui-view></ui-view>
</body>

</html>

helloworld.js

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

myApp.config(function ($stateProvider) {
  $stateProvider.state('hello', {
    url: '/hello',
    component: 'hello'
  });
});

angular.module('bar', []);

component.js

angular
    .module('foo', ['bar'])
    .controller('controller', controller);

controller.$inject = ['barService'];

function controller(barService) {
    var self = this;

    self.greeting = 'hello';
    var serviceHello = barService.hello;

    self.toggleGreeting = function () {
        self.greeting = (self.greeting == 'hello') ? serviceHello : 'hello'
    }
}

angular.module('foo')
    .component('hello', {
        controller: 'controller',
        template: `
              <h3>{{$ctrl.greeting}} Solar System!</h3>
              <button ng-click="$ctrl.toggleGreeting()">toggle greeting</button>
`,
    })


service.js

(function () {
    'use strict';

    angular
        .module('bar')
        .service('barService', barService);

    function barService() {

        this.hello = "hello from service"

    }
})(); 

现在它不起作用,因为'$ stateProvider'不能正确注入。如果将barService移至模块 foo ,它将开始正常工作。

如何将模块正确地插入模块?

0 个答案:

没有答案