如何使用ui路由器在组件驱动架构中定义控制器

How to define a controller in Component Driven Architecture using ui-router?

本文关键字:定义 控制器 ui 何使用 路由器 组件      更新时间:2023-09-26

如何使用Ui Router在组件驱动架构中定义控制器?

状态包含在App.js中,控制器定义在各个组件文件夹中。

$stateProvider.state('route1', {
    url:'/route1',
    views: {
      "ViewA": {
        templateUrl: 'View.html',
        controller: 'ViewController'
      }
    }
  })

(function(myApp) {
var ViewController = function($scope) {
    $scope.message='AngularJS'
};
ViewController.$inject = ['$scope','$http'];
myApp.controller('ViewController', ViewController);}(angular.module('myApp')));

<div ng-controller="ViewController" ><label> {{message}}</label>

如果你所说的"组件驱动架构"是指你的应用程序在各个组件文件夹中有独立的模块,

1.在各自的文件夹中创建组件模块,并将控制器连接到它们

如果模块和控制器都在同一个文件中,您可以这样做:

angular.module('myComponent', []).controller(function($scope) {
    //Code here
});

或者,如果控制器在另一个文件中,你可以像这样获得对你的模块的引用:

angular.module('myComponent').controller(function($scope) {
        //Code here
    });

2.将组件注入主模块:

angular.module('myApp', ['myComponent'])

这样,您的组件控制器就可以在主模块和$stateProvider配置中使用。


还要注意,您不必在View.html中使用ng-controller。当您在更改状态时说controller: 'ViewController'时,这将自动完成。