Changing Element Colour on Hover AngularJS

后端 未结 6 761
失恋的感觉
失恋的感觉 2021-02-07 12:50

So, I\'m just getting started with angularjs and I\'m already confused. I want to change the colour of a list element that corresponds to a hex code colour that is in an array.

6条回答
  •  情深已故
    2021-02-07 13:30

    There is no ng-hover directive. You'll want to use ng-mouseenter and ng-mouseleave.

    Also, keep in mind that the syntax for ng-style is an object corresponding the CSS key-value pairs.

  • $scope.changeColor = function(person) {
        $scope.personColour = {color: '#'+person.colour};
    };
    

    If you'd like for the color to change back to what it was before you hovered, you can create two functions, or pass a parameter to $scope.changeColour:

  • $scope.changeColor = function(person, bool) {
        if(bool === true) {
            $scope.personColour = {color: '#'+person.colour};
        } else if (bool === false) {
            $scope.personColour = {color: 'white'}; //or, whatever the original color is
        }
    };
    

    To take it a step further

    You could create a directive for each person.

    
    

    // your module, then...
    .directive('person', [function() {
        return {
            restrict: 'E',
            replace: true,
            template: '
  • {{i.person_name}}
  • ', link: function(scope, elm, attrs) { elm .on('mouseenter',function() { elm.css('color','#'+i.colour); }) .on('mouseleave',function() { elm.css('color','white'); }); } }; }]);

提交回复
热议问题