为什么不NG-单击我的指导工作,我怎么添加切换类? [英] Why doesn't ng-click work in my directive and how do I add a toggle class?

查看:90
本文介绍了为什么不NG-单击我的指导工作,我怎么添加切换类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个角指令看起来像这样:

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

angular.module('msfApp')
    .directive('listitem', function () {
        return {
            templateUrl: 'assets/templates/directives/listitem.html',
            restrict: 'E',
            scope: {
                'item': '='
            }
        }
    });

和模板看起来像这样:

<div class="tsProductAttribute" ng-click="toggleInBasket(item)">
    <span class="tsProductAttribute-image">
        <img ng-src="{{item.variants[0].image}}">
    </span>
    <span class="tsProductAttribute-desc">{{item.productName}}</span>
    <span class="tsProductAttribute-price">{{item.variants[0].price[0].amount}} {{item.variants[0].price[0].entity}}</span>
</div>

但是现在我有两个问题:


  1. 的NG-点击功能在我的控制器不火, toggleInBasket(项目),这是为什么?

  2. 其次,我怎么添加切换行为列表项,使其切换一个名为tsProductAttribute - 选择类

  1. The ng-click function doesn't fire in my controller, toggleInBasket(item), why is that?
  2. And secondly, how do I add a toggle behaviour to the list item so that it toggles a class called "tsProductAttribute--selected"

在此先感谢你们!

推荐答案

1)问题是隔离范围。你不能看到控制器范围内的功能。一种解决方案是通过函数参照指令:

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:

<一个href=\"http://plnkr.co/edit/GorcZZppa8qcIKbQAg2v?p=$p$pview\">http://plnkr.co/edit/GorcZZppa8qcIKbQAg2v?p=$p$pview

<body ng-controller="ItemController">
  <listitem item="item" item-click="toggleInBasket(item)"></listitem>
</body>

在指令:

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

和在模板:

<div class="tsProductAttribute" ng-click="itemClick(item)">

2)的指令创建另一个函数来切换选中状态,并调用控制器功能:

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);
      }
    }
  }
});

和切换模板类:

<div class="tsProductAttribute" 
    ng-class="{'tsProductAttribute--selected': selected}" 
    ng-click="toggleState(item)">

这篇关于为什么不NG-单击我的指导工作,我怎么添加切换类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆