在AngularJS中的另一个控制器中使用控制器 [英] Using controller inside another controller in AngularJS

查看:109
本文介绍了在AngularJS中的另一个控制器中使用控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我不能在第二个控制器内绑定到控制器的变量?

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"];
}]);

示例: https://jsfiddle.net/nukRe/135/

第二个ng-repeat无效.

Second ng-repeat doesn't work.

推荐答案

在使用controllerAs时,应在控制器中使用this关键字

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"];
}]);

> 分叉的小提琴

注意

从技术上讲,您应该一次遵循一种方法.不要混淆 这两个模式一起使用controllerAs语法/Normal 控制器声明,就像您使用$scope

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

这篇关于在AngularJS中的另一个控制器中使用控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆