角指令,结合点击事件外界因素不工作 [英] Angular directive, binding click event to outside element not working

查看:145
本文介绍了角指令,结合点击事件外界因素不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图与角度切换创建一个自定义事件。该指令被称为可切换。

I am trying to create a custom event for toggling with Angular. The directive is called toggleable.

这听起来起初微不足道,但棘手的一​​点是,我希望能够使用网页上的任何按钮或链接切换。

It sounds trivial at first, but tricky bit is that i want to be able to to use any button or link on the page for toggling.

在code我写的,如下

The code i have written is as below

指令

'use strict';

angular.module('onsComponents')
.directive('togglable', function() {
return {
  restrict: 'A',
  transclude: true,
  scope: {
    togglerId: '@',
    show: '@'
  },
  link: function(scope, element, attrs) {
    if (!scope.togglerId) {
      console.error("Toggler id must be given")
      return
    }

    scope.visible = (scope.show === 'true')
    scope.toggle = function() {
      alert("Before " + scope.visible)
      scope.visible = !scope.visible
      alert("After " + scope.visible)
    }

    //Bind click event to given dom element
    angular.element('#' + scope.togglerId).bind("click", function() {
      scope.toggle()
    })


  },
  templateUrl: 'app/components/toggler/toggler.html'
  }
  })

模板

<div ng-transclude ng-show="visible">

</div>

视图

<a href="" id="toggleButton" >Click me to toggle</a>
<div togglable toggler-id="toggleButton">
  Hey
</div>

肘杆似乎是工作。我可以看到警报链接被点击的时候。麻烦的是没有出现的内容。这似乎是链接是不是真的是在与内容相同的范围,创建另一个范围,当我做到这一点。

The toggle link seems to be working. I can see the alerts when the link is clicked. The trouble is the content does not appear. It seems like the link is not really is in the same scope with the content, another scope is created when i do this.

如果我移动模板中点击链接如下,它的工作原理。但是,这是不是真的我想要什么。

If i move the click link within the template as below, it works. But that is not really what i want.

<!-- Move the link inside template -->
<a href=""  ng-click="toggle()" >Click me to toggle</a>
<div ng-transclude ng-show="visible">

</div>

所以,我怎么能做到这一点?

So how can i achieve that ?

推荐答案

您必须调用范围。$适用()每次你改变的东西,角手表时间之外。通过的之外的我的意思是使用jQuery API绑定事件 - 或者角以外的原生 NG-点击任何其他方式

You have to call scope.$apply() every time you are changing stuff that Angular watches outside of Angular. By outside I mean events bound using the jQuery API - or any other way besides Angular's native ng-click etc.

所以,做任何

scope.toggle = function() {
    scope.visible = !scope.visible;
    scope.$apply();
}

或者

scope.toggle = function() {
    scope.$apply(function() {
        scope.visible = !scope.visible;
    });
}

这篇关于角指令,结合点击事件外界因素不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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