【问题标题】:Defining controllers using ui-router使用 ui-router 定义控制器
【发布时间】:2016-06-25 07:28:44
【问题描述】:

我在 ES6 中使用 Angular js 创建 Web 应用程序。我刚开始学习角度。我有以下问题,我从互联网资源中无法理解。

1) 我正在使用 ui-router 进行基于状态的路由。我的控制器中有以下代码

myApp.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home);
        $stateProvider
            .state('contact', {
            url: '/contact',
            templateUrl: 'contact.html',
           controller: myContactController
        });
};

联系方式.html:

<div ng-controller=”myContactController”>
….
</div>

问题:

a) 我已经在 js 中指定了我所在州的控制器。我是否还需要在我的视图中使用 ng-controller 指定控制器?有什么区别,为什么有必要?

2) 我的应用有一个基本模块。

基础模块 - Index.js:

import subapp1 from  ‘./subApp1/index’;
angular.module(“myapp”,[subapp1]);

subApp1/index.js

Export default function(){
Angular. module(“subApp1”,[]);
};

问题: a)这是将子模块依赖项注入基本模块的正确方法吗?如果不是,那么将模块依赖项注入基本模块的最佳方法是什么? b) 如果我能获得最佳链接,以基本方式了解 Angular js 中的依赖注入和不同范围,我将不胜感激。

【问题讨论】:

    标签: angularjs angular-ui-router


    【解决方案1】:

    我已经在 js 中指定了我所在状态的控制器。我是否还需要在我的视图中使用 ng-controller 指定控制器?有什么区别,为什么有必要?

    您不需要在 HTML 中使用 ngController。路由器将获取 HTML 模板并使用指定的控制器对其进行编译。

    我的应用有一个基本模块...

    您通过名称指定依赖模块,因此您的设置可能如下所示(注意,您如何导出 Angular 模块的 name 属性):

    export default angular.module('subApp1', [])
      .factory('someService', semeService) // For example, attach some module service
      .directive('someDirective', someDirective) // ... or some components
      .name;
    

    然后

    import subapp1 from './subApp1/index';
    import subapp2 from './subApp2/index';
    
    angular.module('myapp', [
      subapp1,
      subapp2
    ]);
    

    【讨论】:

      【解决方案2】:

      1.a) 不,你不应该。如果这样做,您将拥有两个控制器实例

      2.a) 没有。首先,您不要将一个模块“注入”到另一个模块中:一个模块依赖于另一个模块,仅此而已。这与依赖注入无关。其语法是

      angular.module('myapp', ['subApp1']);
      

      即数组的元素必须是您所依赖的模块的名称。当然,这些模块必须自己定义(之前或之后,没关系),使用

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

      2.b)https://docs.angularjs.org/guide

      【讨论】:

        猜你喜欢
        • 2016-02-18
        • 1970-01-01
        • 1970-01-01
        • 2015-06-02
        • 1970-01-01
        • 1970-01-01
        • 2016-01-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多