Search code examples
javascriptangularjsangular-ngmodel

ngModel on a img


I'm trying to make something easy but, it doesn't work. I have this html

<div  class="positionDiv">
     <img class="eyes" ng-model="showPasswordIsChecked" ng-click="afficherMdp()"  ng-controller="creationCompteController"  src="images/eye.png" />
</div>
{{ showPasswordIsChecked }}

and this javascript

angular.module('starter').controller('creationCompteController',[
    '$scope',   
     function ($scope)
    {


        $scope.showPasswordIsChecked = false;


        //Affichage du template html
        $scope.afficherMdp = function()
        {
            if($scope.showPasswordIsChecked==true)
            {
                $scope.showPasswordIsChecked=false;
                alert($scope.showPasswordIsChecked);
            }else{
                $scope.showPasswordIsChecked=true;
                alert($scope.showPasswordIsChecked);
            }

        }

    }]);

I want, when i click on my image to change the value of showPassword to true or false. In the js file, the enter in the function, but in the html {{ showPasswordIsChecked }} shows nothing, as if the variable doesn't exist. How could I do please ?


Solution

  • You can't bind an <img /> to a variable with ng-model :https://docs.angularjs.org/api/ng/directive/ngModel

    You must use it on an input (or an element with an input behavior).

    But you can do like this :

    angular.module('test', []).controller('creationCompteController', function($scope) {
      $scope.showPasswordIsChecked = false;
    });
    #my-checkbox {
      visibility: hidden;
      opacity: 0;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
    <div ng-app="test">
      <div ng-controller="creationCompteController">
          <label for="my-checkbox">
              <input id="my-checkbox" type="checkbox" ng-model="showPasswordIsChecked" />
              <img src="http://icons.iconarchive.com/icons/custom-icon-design/mono-general-4/128/eye-icon.png" />
          </label>
        
           {{ showPasswordIsChecked }}
      </div>  
    </div>