问题描述
为什么我不能绑定到第二个控制器内的控制器变量?
<div ng-controller="MainCtrl">主要的:<div ng-repeat="state in states">{{状态}}<div ng-controller="InsideCtrl as inside">里面:<div ng-repeat="state in inside.states2">{{状态}}
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 = 这个;vm.states2 = ["NY", "CA", "WA"];}]);
注意
从技术上讲,您应该一次遵循一种方法.不要混淆这两种模式一起使用,要么使用 controllerAs
语法/普通使用 $scope
MainCtrl
所做的控制器声明Why I can't bind to controller's variable inside 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/
Second ng-repeat doesn't work.
As you are using controllerAs
you should be using this
keyword in controller
angularApp.controller('InsideCtrl', [ function() {
var vm = this;
vm.states2 = ["NY", "CA", "WA"];
}]);
NOTE
这篇关于在 AngularJS 中的另一个控制器中使用控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!