在 AngularJS 的另一个控制器中使用控制器
Using controller inside another controller in AngularJS
为什么我不能绑定到第二个控制器中的控制器变量?
<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"];
}]);
示例:https://jsfiddle.net/nukRe/135/
第二次 ng-repeat 不起作用。
当您使用 controllerAs
时,您应该在控制器中使用 this
关键字
angularApp.controller('InsideCtrl', [ function() {
var vm = this;
vm.states2 = ["NY", "CA", "WA"];
}]);
注意
Technically you should follow one approach at a time. Don't mix up
this two pattern together, Either use controllerAs
syntax/ Normal
controller declaration as you did for MainCtrl
using $scope
删除
as inside
从这里开始:
<div ng-controller="InsideCtrl as inside">
这样:
`<div ng-controller="InsideCtrl">`
<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>
为什么我不能绑定到第二个控制器中的控制器变量?
<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"];
}]);
示例:https://jsfiddle.net/nukRe/135/
第二次 ng-repeat 不起作用。
当您使用 controllerAs
时,您应该在控制器中使用 this
关键字
angularApp.controller('InsideCtrl', [ function() {
var vm = this;
vm.states2 = ["NY", "CA", "WA"];
}]);
注意
Technically you should follow one approach at a time. Don't mix up this two pattern together, Either use
controllerAs
syntax/ Normal controller declaration as you did forMainCtrl
using$scope
删除
as inside
从这里开始:
<div ng-controller="InsideCtrl as inside">
这样:
`<div ng-controller="InsideCtrl">`
<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>