mercredi 17 août 2016

AngularJS - How do I check a checkbox inside of a directive?

I am new to AngularJS so I am still trying to get a grasp on the best practices and the "Angular way" of doing things. With that being said, here is my situation:

I am trying to submit an AngularJS form. Part of the form is a list of blog names that I want the user to choose from. Inside each <li> is a checkbox. When the user clicks on the li, I want to check the checkbox so that when the form is submitted, it records the selected blog names.

<li>
    <div>
        <img ng-src="" />
    </div>
    <div>
        
    </div>
    <input type="checkbox" name="blogs[]" value="" style="display: none">
</li>

Now, I need this exact list item in 3 different lists. So I thought the way I should do it, is make it a directive:

The JS

angular
  .module('app')
  .directive('blogSelect', function(){
    return {
        restrict: 'E',
        template: '<li ng-click="onClick()"><div><img ng-src="" /></div><div ></div><input type="checkbox" name="blogs[]" value="" style="display: none"></li>',
        replace: true,
        scope: {
            image: '@image',
            name: '@name'
        },
        link: function($scope, $element, attrs) {
        $scope.onClick = function() {
            $element.toggleClass("selected");

            var checkbox = $element.find('input[type="checkbox"]');
            checkbox.attr("checked", !checkbox.attr("checked"));
        }
      }
    };
  });

The HTML

<ul ng-if="vm.blogs.length">
   <blog-select ng-repeat="blog in vm.blogs"
       name=""
       image="/url/to/img/.jpg">
   </blog-select>
</ul>

Something doesn't seem right here. The checkbox variable in the onClick function is undefined. After some research, I don't think I am doing it the correct way. Should I be controlling the checkbox based on an array in my model (where the vm.blogs is coming from)? I can't seem to find anything that describes what to do with a custom checkbox directive in my situation.

But then again, maybe I'm not even going about it the right way? Any wisdom, insight, and/or help is appreciated. Thanks!

Aucun commentaire:

Enregistrer un commentaire