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

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

问题描述

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

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

Forked Fiddle

NOTE

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天全站免登陆