Angularjs - 只调用许多子控制器/多个控制器中的一个

时间:2015-07-24 01:08:10

标签: angularjs subcontroller

我有一个索引页面,其中我定义了两个控制器。我想总是调用一个主控制器(应该总是渲染)而另一个只调用特定的子URL调用。我应该将一个嵌套在另一个中,还是让它们彼此独立?我没有权限更改路由或任何东西,只有控制器。 现在,当我使用提到的模板(HTML)时,它调用/呈现两个控制器,即使url是say / index

Only for /index/subPage, I want both controllers to be rendering. 

/index
/index/subPage

HTML:

<div ng-controller="MainCtl" ng-init=initMain()>        
    <p> Within ctller2 {{results}} </p>
</div>


<div ng-controller="Ctller2">       <!-- should not be displayed unless /subPage/mainUrl is rendering -->
    <p> Within ctller2 {{results}} </p>
</div>

JS:

app.controller('MainCtl', ['$scope', '$http', '$location', function ($scope, $http, $location) {

    $http.get('xx/mainUrl').then(function(data) {
        $scope.results = someDataJSON;
        console.log(someDataJSON);
    });

    $scope.initMain = function() {      
            $scope.initMethods();   
    }   
}]); 


app.controller('Ctller2', ['$scope', '$http', '$location', function ($scope, $http, $location) {
 // This controller gets initialized/rendered/called even when xx/mainUrl is called, and when xx/subPage/mainUrl is called too.. 
    $http.get('xx/subPage/mainUrl').then(function(data) {
        $scope.results = someDataJSON;
        console.log(someDataJSON);
    })

    $http.get('xx/subPage').then(function(data) {
        $scope.results = data.data;
        console.log(data);
    })

   angular.element(document).ready(function () {
     alert('Hello from SubCtl, moving over from main controller to here');
    });


}]);

我做错了什么?我是Angular.js的新手

1 个答案:

答案 0 :(得分:2)

您可以使用ng-if有条件地启动控制器。所以你可以尝试这样的事情:

<body ng-controller="MainCtrl">

    <div ng-controller="ctrl1">{{hello}}</div>
    <div ng-controller="ctrl2" ng-if="showCtrl2">{{hello}}</div>

</body>

然后使用$location.path()检查当前网址,在父控制器中设置变量的值

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

app.config(function($locationProvider){
    $locationProvider.html5Mode(true); 
});

app.controller('MainCtrl', function($scope, $location) {
  $scope.showCtrl2 = ($location.path() === 'my path');
});

app.controller('ctrl1', function($scope){
  $scope.hello = 'ctrl1 says hello';
});

app.controller('ctrl2', function($scope){
  $scope.hello = 'ctrl2 says hello';
});

但它有点hacky,对于更大的项目,更强大的解决方案需要使用类似ui.router的东西。