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

Angularjs - Calling only one of many subcontrollers/ multiple controllers

我有一个索引页,其中我定义了两个控制器。我想始终调用一个主控制器(应该始终呈现),而另一个仅针对特定的子 URL 调用调用。我应该让一个嵌套在另一个中,还是让它们彼此独立?我无权更改路线或任何其他内容,只能使用控制器。 现在,当我使用提到的模板 (HTML) 时,它 calls/renders 两个控制器,即使 url 是说 /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

的新手

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

<body ng-controller="MainCtrl">

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

</body>

然后通过使用 $location.path()

检查当前 url 在父控制器中设置变量的值
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';
});

但这有点老套,对于更大的项目,更强大的解决方案需要使用类似 ui.router.

的东西