在离心相同的视图中使用多个控制器

时间:2016-11-28 08:46:52

标签: javascript html angularjs ionic-framework

我在此视图中有一个控制器名称为"Listctrl"的视图,我想要一个名为"LocationCtrl"的不同控制器。目前我这样做:

路由

 .state('list', {
        url: '/list',
        templateUrl: 'templates/list.html',
        controller: "ListCtrl",
        cache: false
      })

HTML(list.html)

<ion-view ng-init="ini()" ng-controller="LocationCtrl">
  <ion-header-bar class="banner-top ext-box" align-title-h="left">
    <div class="int-box2"><h2 id="s_back1">STORIE</h2></div>
  </ion-header-bar>
<ion-content class="has-header has-footer no-bgColor start" overflow-scroll="false" has-bouncing="false">
<div class="container-list">

我该如何正确解决这个问题?我需要两个控制器用于相同的视图,但在不同的地方,因为我想在不同的视图中重用控制器代码。

目前<ion-view ng-init="ini()" ng-controller="LocationCtrl"> 不运行LocationCtrl

任何帮助非常感谢!

2 个答案:

答案 0 :(得分:1)

一个视图不可能有两个控制器,因为这没有意义。如果您具有应共享的功能,请使用控制器继承,但仅当LocationCtrl将其方法添加到$scope时才可以这样做:

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

app.controller('LocationCtrl', function($scope) {
  // I have functionality to share
});

app.controller('ListCtrl', function($scope, $controller) {
  $controller('LocationCtrl', {$scope: $scope}); // This adds properties to ListCtrl's scope
});

另一种方法可能是将ng-controller="LocationCtrl"放到包装器div:

<ion-view ng-init="ini()">
  <div ng-controller="LocationCtrl">
       <ion-header-bar class="banner-top ext-box" align-title-h="left">
          <div class="int-box2"><h2 id="s_back1">STORIE</h2></div>
       </ion-header-bar>

但这似乎不是一个好选择。更好的方法是使用LocationCtrl上定义的功能创建一个组件/指令,并在视图中的某处使用它:

<ion-view ng-init="ini()">
  <component-with-location-ctrl-functionality></component-with-location-ctrl-functionality>

答案 1 :(得分:0)

如果您为路线设置控制器“ListCtrl”,并且您想要使用另一个控制器在此路径中创建位置,则可以创建具有隔离范围的指令

app.directive('yourNewDrctv', function() {
    return {
        restrict: 'E',
        templateUrl: 'yourNewTmpl.html',
        scope: {},
        controller: 'yourNewCtrl'
    };
});

并在任何地方的模板“templates / list.html”中使用它 就像那样:

<your-new-drctv></your-new-drctv>