Using a controller inside another controller in AngularJS

Why can't I bind to a controller variable inside the second controller?

<div ng-app="ManagerApp"> <div ng-controller="MainCtrl"> Main: <div ng-repeat="state in states"> {{state}} </div> <div ng-controller="InsideCtrl as inside"> Inside: <div ng-repeat="state in inside.states2"> {{state}} </div> </div> </div> </div> var angularApp = angular.module('ManagerApp', []); angularApp.controller('MainCtrl', ['$scope', function ($scope) { $scope.states = ["NY", "CA", "WA"]; }]); angularApp.controller('InsideCtrl', ['$scope', function ($scope) { $scope.states2 = ["NY", "CA", "WA"]; }]); 

Example: https://jsfiddle.net/nukRe/135/

The second ng-repeat does not work.

+6
source share
3 answers

When you use controllerAs , you must use the this in the controller

 angularApp.controller('InsideCtrl', [ function() { var vm = this; vm.states2 = ["NY", "CA", "WA"]; }]); 

Forked fiddle

Note

Technically, you have to follow one approach at a time. Do not mix this two patterns together, or use the controllerAs / Normal syntax as you did for MainCtrl using $scope

+3
source

Remove

like inside

from here:

<div ng-controller="InsideCtrl as inside"> such that:

 `<div ng-controller="InsideCtrl">` 
0
source
 <div ng-app="ManagerApp"> <div ng-controller="MainCtrl"> Main: <div ng-repeat="state in states"> {{state}} </div> <div ng-controller="InsideCtrl"> Inside: <div ng-repeat="state in states2"> {{state}} </div> </div> </div> </div> 
-1
source

Source: https://habr.com/ru/post/988467/


All Articles