javascriptangularjsangularjs-directiveangularjs-ng-repeatangularjs-ng-init

Expression in ng-init not working with ng-repeat


So I am trying to have many divs with background images and disable the background image when I hover over any particular div.

<div id="interest" class="col-md-4 col-sm-6" ng-repeat="interest in vm.interestList"
     ng-init="myStyle={'background-image': 'url(interest.src)'}"
     ng-style="myStyle" ng-mouseenter="myStyle={}"
     ng-mouseleave="myStyle={'background-image': 'url(interest.src)'}">
    <button id="interestButton" class="btn btn-default btn-lg" >{{interest.interestName}}</button>
</div>

For some reason the myStyle in ng-init never gets the actual value in interest.src rather just gets 'interest.src'. I also tried {{interest.src}} but that does not work.

Any help is appreciated!!


Solution

  • Try this

    var jimApp = angular.module("mainApp",  []);
    
    jimApp.controller('mainCtrl', function($scope){
      
      $scope.interestList = [{interestName:"One", src:"img/one.png"}];
      $scope.url = function(url){
        return 'url('+url+')';
      };
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="mainApp" ng-controller="mainCtrl">
    
      <div id="interest" class="col-md-4 col-sm-6" ng-repeat="interest in interestList"
         ng-init="myStyle = {'background-image': url(interest.src)}"
         ng-style="myStyle" ng-mouseenter="myStyle={}"
         ng-mouseleave="myStyle={'background-image': url(interest.src)}">
        <button id="interestButton" class="btn btn-default btn-lg" >{{interest.interestName}}</button>
      </div>
    </div>