AngularJS,指令中的链接函数,单击按钮时如何更新属性?

我是 AngularJS 的新手,我正在尝试一些东西。有时成功,有时不成功。这是我(未成功)尝试做的事情:用户单击一个按钮,然后计算足球比赛的随机分数。根据我们的团队是赢还是输,显示的消息会发生变化。这行得通。但不起作用的是我希望我的 css 类也发生变化。我试图通过指令中的链接函数来做到这一点(因为我目前正在学习链接和编译函数),但似乎属性在应用程序启动时加载一次,并且不会被修改。好的,也许我应该分享我的代码:


1/ 我的 index.html 中有趣的部分


    <div class="container" ng-controller="ScoreController as score">

        <h4> {{ score.test }} </h4>

        <button class="btn btn-danger" ng-click="score.scoreCalculation();">Check the score</button>

        <div display-result class="grey" result="{{ score.result }}">

           <h4> {{ score.message }} </h4>

        </div>

    </div>

2/ 我非常简单的 css 文件


.grey {

    border: solid grey 5px;

    border-radius: 7px;

}


.win {

    border: solid green 5px;

}


.lose {

    border: solid red 5px;

}


.draw {

    border: solid orange 5px;

}

3/我的控制器


function ScoreController () {

    // ctrl = this;

    this.message = "The game is about to start!";

    this.scoreFrance = 0;

    this.scoreArgentine = 0;

    this.test = "France - Argentine";

    // this.result = "";

    this.color = "";

    this.scoreCalculation = () => {

        let France = Math.floor(Math.random() * 4);

        let Argentine = Math.floor(Math.random() * 4);


        if (France > Argentine) {

            this.message = `France Wins! ${France} - ${Argentine}`;

            this.result = "win";

        } else if (France < Argentine) {

            this.message = `France Loses! ${France} - ${Argentine};`

            this.result = "lose";

        } else {

            this.message = `It's a draw! ${France} - ${Argentine}`;

            this.result = "draw";

        };

    };

};


angular

    .module('app')

    .controller('ScoreController', ScoreController);

4/ 我的指令


function displayResult () {

    return {

        restrict: 'A',

        link: function ($scope, $element, $attrs) {

            $element.addClass($attrs.result);

        }

    };

};


angular

    .module('app')

    .directive('displayResult', displayResult);

现在,我希望由于result="{{ score.result }}"我通过 传递给我的指令attrs,我的消息的 css 类将被更新。但是不, attrs.result当我 console.log 它们时,它们保持在最初的值。


有知道方法的请告知,谢谢!


有只小跳蛙
浏览 145回答 1
1回答

慕码人8056858

link每个指令在初始化时运行一次,在这里你想在那之后更新类,对于 attrs,它是用 observe 完成的:link: function ($scope, $element, $attrs) {&nbsp; &nbsp; attrs.$observe('result', (value) => {&nbsp; &nbsp; &nbsp; &nbsp; $element.addClass(value);&nbsp; &nbsp; });}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript