1

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

4

1 回答 1

2

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

<body ng-controller="MainCtrl">

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

</body>

然后通过使用检查当前 url 在父控制器中设置变量的值$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.

于 2015-07-24T01:58:22.383 回答