Why doesn't ng-click work in my directive and how do I add a toggle class?

后端 未结 3 1957
清酒与你
清酒与你 2021-01-15 15:47

I\'ve created a directive in Angular that looks like this:

angular.module(\'msfApp\')
    .directive(\'listitem\', function () {
        return {
                    


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-15 16:10

    1) Problem is the isolated scope. You cannot see the function in the controller scope. One solution is to pass the function reference to the directive:

    http://plnkr.co/edit/GorcZZppa8qcIKbQAg2v?p=preview

    
      
    
    

    in the directive:

    scope: {
        'item': '=',
        'itemClick': '&'
    }
    

    and in the template:

    2) Create another function in the directive to toggle selected state and call the controller function:

    angular.module('msfApp').directive('listitem', function () {
      return {
        templateUrl: 'listitem.html',
        restrict: 'E',
        scope: {
          'item': '=',
          'itemClick': '&'
        },
        link: function(scope, iElement, iAttrs) {
          scope.selected = false;
          scope.toggleState = function(item) {
            scope.selected = !scope.selected;
            scope.itemClick(item);
          }
        }
      }
    });
    

    and toggle the class in the template:

提交回复
热议问题