将自定义javascript事件绑定到angular [英] Bind custom javascript event to angular

查看:100
本文介绍了将自定义javascript事件绑定到angular的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个移动应用程序,其中列出了一些项目.可以下拉此列表以启动列表刷新(我使用的是iScroll4).我现在正在尝试将此事件挂接到我的角度控制器,以便我可以进行api调用并更新模型.

I'm working on a mobile application where I have list with some items. This list can be pulled down to inititate a refresh of the list (I'm using iScroll4). I'm now trying to hook this event up to my angular controller so I can make an api call and update the model.

javascript基本上如下:

The javascript is basically as follows:

[..] //javascript code to detect the pulldown event

function pullDownAction(){
     //I want to update the scope here
}

根据我所读的内容,我需要做出一个角度指令并从那里调用该事件,但是我仍然不知道上面的代码应该去哪里.

Based on what I have read, I need to make an angular directive and call the event from there, but I still haven't figured out where the above piece of code should go.

我也尝试过在pullDownAction函数中广播事件,并在控制器中监听它,就像这样:

I have also tried broadcasting the event from within the pullDownAction function and listening to it in the controller, like so:

function pullDownAction(){
    var $rootScope = angular.injector(['ng']).get('$rootScope');
    $rootScope.$apply(function(){
          $rootScope.$broadcast('updateInbox');
    });
});

,然后在控制器中:

$scope.$on('updateInbox', function(){
     $http.get(apiUrl)
         .success(function (data) {
              $scope.model = data;
        });           
});

但是我确定我错过了一些重要的东西,这些东西使代码无法正常工作.我对angular还是很陌生,所以我还没有真正了解指令的工作原理.

But I'm sure I'm missing something important which makes the code not work. I'm quite new to angular, so I haven't really gotten the hang of how directives work yet.

推荐答案

我通过将事件的所有javascript代码放入链接函数来使其工作:

I made it work by putting all the javascript code for the event in the link function:

app.directive('pullToRefresh', function () {
return {
    restrict: 'AC',
    link:
    function (scope, element, attr) {
            //Code to detect when element is pulled goes here

            function pullDownAction(){
                 scope.$eval(attr.pulldown);
            }

然后我只是在名为pulldown的容器中放置一个属性,它们现在可以访问相同的作用域.我的元素看起来像这样:

I then just put an attribute in the container called pulldown, and they now have access to the same scope. My element looks like this:

<div class="pull-to-refresh" pulldown="update()">
   //Element to be "pull-to-refreshable" here
</div>

update()当然是控制器中的一个函数,您可以在其中做任何想做的事情!

update() is of course a function in the controller where you can do whatever you want!

这篇关于将自定义javascript事件绑定到angular的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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