使用ng-click更改布尔变量的值

时间:2016-09-25 02:41:02

标签: angularjs

我是AngularJS的新手,我正在制作一个网络应用程序,根据团队的哪一天,该应用程序应根据某些游戏进行过滤。我尝试使用ng-click更改布尔变量的值,但它似乎没有按预期工作。

这是我的HTML

<body ng-controller="MatchupController as matchupCtrl">
    <div class="jumbotron" ng-controller="DayController as DayCtrl">

    <button type="button" class="btn btn-info" ng-click="tnf()">Thursday Games</button>

</div>

<div class="row" ng-repeat="team in matchupCtrl.teams" ng-hide="team.tnf">
    <div class="col-sm-5 well">
        <h3>Home</h3>
        {{team.home.name}}
    </div>
    <div class="col-sm-5 well" >
        <h3>Away</h3>
        {{team.away.name}}
    </div>

</div>

......和我的JS

var app = angular.module('mainApp', []);
app.controller('MatchupController',function(){
   this.teams = matchUps;

});


var matchUps = [
{
    home:{ 
        name:'Cincinnati Bengals',
        homeImage:{'background-image': 'url(http://prod.static.bengals.clubs.nfl.com/assets/img/gbl-hd-bg.jpg)'},
    },
    away:{ 
        name:'Miami Dolphins',
    awayImage:{'background-image': 'url(http://blog-imgs-70.fc2.com/o/f/f/offseason2012/Dolphins.jpg)'},
},
    location: 'Paul Brown Stadium, Cincinnati',
    time: '8:25pm',
    date: "2016-09-29",
    tnf: false,
},
{
    home:{
        name:'Jaxonville Jaguars',
        homeImage:{'background-image':     'url(http://nfasl.spruz.com/gfile/75r4!-!JEHJEG!-!zrzor45!-!LJPKNQQG-JJSJ-    HHMR-NNJR-EPLFJOMGLIMD/jacksonville_jaguars_banner.jpg)'},
    },
    away:{
        name:'Indianapolis Colts',
        awayImage: {'background-image': 'url(http://www.851facebook.com/images/sports-nfl-afc-south-indianapolis_colts-night-football-rugby-facebook-timeline-cover-banner-for-fb-profile.jpg)'},
    },
    location: 'Wembley Stadium, London',
    time: '9:30am',
    date: "2016-10-02",
    snf: false,
           },
{
    home: {
        name:'Minnesota Vikings',
        homeImage: {'background-image': 'url(http://611enterprises.com/wp-content/uploads/2014/11/Minnesota_Vikings_banner.jpg)'},  
    },
    away: {
        name: 'New York Giants',
        awayImage: {'background-image': 'url(http://www.covermyfb.com/media/covers/thumb/3895-new-york-giants.jpg)'},
    },
    location: 'U.S. Bank Stadium, Minneapolis',
    time: '8:30pm',
    date: "2016-10-03",
    mnf: false,
           }
]
app.controller('DayController',function() {
    var tnf = function() {
       matchUps.tnf = !matchUps.tnf;
        return matchUps.tnf;

    }
});

我想更改tnf的值,以便在用户单击按钮时将其隐藏在显示中(即将tnf的值更改为true)。

1 个答案:

答案 0 :(得分:1)

You need to attach tnf() to the controller's scope. The way you have it now, it is simply declared as a local variable and when the controller function finishes, the tnf function goes out of scope and will be garbage collected. Instead, you should do this:

app.controller('DayController',function() {
    this.tnf = function() {
       matchUps.tnf = !matchUps.tnf;
        return matchUps.tnf;
    }
});