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);

现在,我希望由于我通过attrs传递给指令的result="{{ score.result }}",我的消息的css类将得到更新。但不是,attrs.result保持在我控制台.log时的初始值。

如果你知道周围的路,请告诉我,谢谢!

link在初始化时为每个指令运行一次,在此之后,您需要更新类,对于属性,使用observe:

link: function ($scope, $element, $attrs) {
attrs.$observe('result', (value) => {
$element.addClass(value);
});
}

最新更新