Issue
I am new to AngularJS and I am trying out some stuff. Sometimes successfully, sometimes not. Here is what I am (unsuccessfully) trying to do: The user clicks a button, and a random score for a football game is calculated. Depending on whether our team wins or loses, the displayed message changes. This works. What doesn't work though is that I want my css class to change as well. I am trying to do that through a link function in the directive (because I am learning the link and compile functions at the moment), but it seems that the attrs are loaded once at the start of the app, and an not be modified. OK, maybe I should share my code:
1/ The interesting part in my 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/ My very simple css file
.grey {
border: solid grey 5px;
border-radius: 7px;
}
.win {
border: solid green 5px;
}
.lose {
border: solid red 5px;
}
.draw {
border: solid orange 5px;
}
3/ My controller
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/ My directive
function displayResult () {
return {
restrict: 'A',
link: function ($scope, $element, $attrs) {
$element.addClass($attrs.result);
}
};
};
angular
.module('app')
.directive('displayResult', displayResult);
Now, I was hoping that thanks to the result="{{ score.result }}" that I am passing to my directive via the attrs, the css class for my message would be updated. But no, the attrs.result stay at the value they were initially when I console.log them.
Let me know if you know a way around, thanks!
Solution
link runs one time for each directive when it initializes, here you want to update class after that, for attrs it is done with observe:
link: function ($scope, $element, $attrs) {
attrs.$observe('result', (value) => {
$element.addClass(value);
});
}
Answered By - Petr Averyanov
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.