Angularjs - Calling only one of many subcontrollers/ multiple controllers -
i have index page wherein define 2 controllers. want call 1 main controller (should rendered always) , other called specific sub url calls. should make 1 nested within another, or can keep them independent of each other? don't have access change routes or anything, controller. right when use template (html) mentioned, calls/renders both controllers, though url /index
only /index/subpage, want both controllers rendering. /index /index/subpage
html:
<div ng-controller="mainctl" ng-init=initmain()> <p> within ctller2 {{results}} </p> </div> <div ng-controller="ctller2"> <!-- should not displayed unless /subpage/mainurl 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) { // controller gets initialized/rendered/called when xx/mainurl called, , when xx/subpage/mainurl 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 subctl, moving on main controller here'); }); }]);
what doing wrong? i'm new angular.js
you can conditionally initiate controller using ng-if
. try this:
<body ng-controller="mainctrl"> <div ng-controller="ctrl1">{{hello}}</div> <div ng-controller="ctrl2" ng-if="showctrl2">{{hello}}</div> </body>
and set value of variable in parent controller checking current url using $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'; });
but it's bit hacky , larger project more robust solution require using ui.router
.
Comments
Post a Comment