跨 View 的 AngularJS 变量(同一 Controller )

标签 angularjs

我有一个 AngularJS 应用程序,它(目前)只有一个 Controller 但有多个 View 。所有这些数据都是通过 $http 提取的。

在一个 View 中,它有一个用于“联盟”的ng-repeat。它有一个带有 ng-click 的按钮,用于获取该联赛的球队数量和每支球队的球员数量,并将它们传递给函数并将它们设置为变量。该函数还使用 $location 将 View 重定向到另一个页面。

在该页面中,它有绑定(bind)来查看这些变量。然而,什么也没有显示。它可以LOG信息,但当 View 改变时它不会显示它。

这是我的 git repo为了它。

  1. leagues.html,第 27 行,用于调用下面列表项 3 中的函数的 ng-click,并将其发送到 team.html。
  2. teams.html,显示变量(为了测试,我只是尝试在创建另一个 ng-repeat 之前显示它们)
  3. public/javascripts/app.js,第 63 行,用于呈现变量的函数。

大多数答案都倾向于说“使用不同的 View ”或“使用 ui-router”。为什么这不起作用?

请参阅下面我的代码片段。

leagues.html

<div class="container col-md-12">
    <h1>Manage Leagues</h1>
    <div class="table-responsive">
        <table class="table">
            <tr>
                <th>League Name</th>
                <th>Location</th>
                <th>Start Date</th>
                <th>Duration</th>
                <th>Team Count</th>
                <th>Courts</th>
                <th>Format</th>
                <th>Manage League</th>
                <th>Add Players</th>
                <th>Archive</th>
            </tr>
            <tr ng-repeat="league in leagues">
                <td>{{league.league_name}}</td>
                <td>{{league.park_location}}</td>
                <td>{{league.start_date | date:'dd-MM'}}</td>
                <td>{{league.league_duration}}</td>
                <td>{{league.team_count}}</td>
                <td>{{league.court_ct}}</td>
                <td>{{league.player_count}}</td>
                <td><a class="btn btn-success">Manage</a></td>
                <!-- This currently only logs that player and team count-->
                <td><button class="btn btn-success" ng-click="createTeam(league.id,league.team_count,league.format)">Add</button></td>
               <!-- //-->
                <td><button class="btn btn-danger" ng-click="archiveLeague(league.id)">Archive</button></td>
            </tr>
        </table>
    </div>
</div>

teams.html

<div class="container">
    <h1>Create Teams</h1>
    <h3>{{current-id}}</h3>
    <h3>{{current-teams}}</h3>
    <h3>{{current-format}}</h3>
    <h3>Done</h3>
</div>

public/javascripts/app.js

/**
 * Created by nhyland on 7/16/15.
 */
var myApp = angular.module('myApp', ['ngRoute']);

myApp.config(function ($routeProvider) {

    $routeProvider
        .when('/', {
            templateUrl: "/pages/main.html",
            controller: 'mainController',
            map: 'main'
        })
        .when('/leagues', {
            templateUrl: "/pages/leagues.html",
            controller: 'mainController',
            map: 'leagues'
        })
        .when('/create', {
            templateUrl: "/pages/create.html",
            controller: 'mainController',
            map: 'create'
        })
        .when('/create/team', {
            templateUrl: "/pages/teams.html",
            controller: 'mainController',
            map: 'teams'
        })
        .otherwise({
            template: "<h1>Page does not exist.</h1>"
        });
});

myApp.controller('mainController', function($scope, $http, $location) {
    $scope.test = "Angular is working";
    $scope.createLeague = function() {
        $scope.league.archived = 0;
        $http.post('/app/create/league', $scope.league)
            .success(function(data) {
                console.log(data);
                $scope.leagueInfo = data;
                $scope.leagues = {};
                $location.path("/leagues");
            })
            .error(function(error) {
                console.log('Error: ' + error);
            });
    };

    function getLeagues() {
        $http.get('/app/leagues/director/' + director)
            .success(function(data) {
                console.log(data);
                $scope.leagues = data;
            })
            .error(function(error) {
                console.log(error);
            })
    }

    getLeagues();

    $scope.createTeam = function(id, teams, format) {
        console.log('League Details: ' + id);
        console.log('League Details: ' + teams);
        console.log('League Details: ' + format);

        $scope.currentId = id;
        $scope.currentTeams = teams;
        $scope.currentFormat = format;

        $location.path('/create/team');

        $scope.getNum = function(num) {
            return new Array(num);
        };
    };

    $scope.archiveLeague = function(id) {
        $http.put('/app/leagues/archive/' + id + '/' + director)
            .success(function(data) {
                console.log(data);
                $scope.leagues = data;
            })
            .error(function(error) {
                console.log(error);
            })
    };
});

最佳答案

它不起作用,因为每次路由更改时,都会创建一个新的 Controller 实例。这意味着您的范围将被重新初始化,因此您会丢失想要保存的值。要看到这一点,只需检查浏览器中的元素并在 Controller 的开头放置一个断点。当您的 View 更改时,您将看到创建了一个新实例。 (你的$scope将会改变)

建议每个 View 只有一个 Controller ,当您想要跨 Controller 共享数据时,建议使用服务或工厂。

关于跨 View 的 AngularJS 变量(同一 Controller ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31528150/

相关文章:

javascript - ionic 框架 : Generating divs dynamically doesn't work

javascript - 递归 ngInclude

javascript - 在 Angularjs 中使用日期过滤器显示休息日的日期

javascript - Angular 指令不会随着作用域的更新而更新

javascript - Angular 不从工厂获取数据

javascript - angularjs如何在html模板中的json对象中进行搜索

arrays - AngularJS 如何获取数组中的最后一条记录

javascript - 为什么我的简单的 Angular 示例不能在 fiddle 上工作?

javascript - Protractor/Selenium with Angular overlay,其他元素会收到点击

javascript - 运行单元测试时 Promise 回调不执行