问题描述
我正在开发一个移动应用程序,其中列出了一些项目.可以下拉此列表以启动列表的刷新(我使用的是 iScroll4).我现在正在尝试将此事件连接到我的 angular 控制器,以便我可以进行 api 调用并更新模型.
javascript基本如下:
[..]//检测下拉事件的javascript代码函数 pullDownAction(){//我想在这里更新范围}
根据我所读到的内容,我需要制定一个 angular 指令并从那里调用事件,但我仍然没有弄清楚上面的代码应该放在哪里.
我还尝试从 pullDownAction 函数中广播事件并在控制器中监听它,如下所示:
function pullDownAction(){var $rootScope = angular.injector(['ng']).get('$rootScope');$rootScope.$apply(function(){$rootScope.$broadcast('updateInbox');});});
然后在控制器中:
$scope.$on('updateInbox', function(){$http.get(apiUrl).成功(功能(数据){$scope.model = 数据;});});
但我确定我遗漏了一些使代码无法正常工作的重要内容.我对 angular 很陌生,所以我还没有真正掌握指令的工作原理.
我通过将事件的所有 javascript 代码放在链接函数中来使它工作:
app.directive('pullToRefresh', function () {返回 {限制:'交流',关联:功能(范围,元素,属性){//检测元素何时被拉出的代码在这里函数 pullDownAction(){范围.$eval(attr.pulldown);}
然后我只是在名为 pulldown 的容器中放置了一个属性,它们现在可以访问相同的范围.我的元素看起来像这样:
//元素在这里是拉到可刷新"的
update() 当然是控制器中的一个函数,你可以在其中做任何你想做的事!
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.
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.
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');
});
});
and then in the controller:
$scope.$on('updateInbox', function(){
$http.get(apiUrl)
.success(function (data) {
$scope.model = data;
});
});
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.
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);
}
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() is of course a function in the controller where you can do whatever you want!
这篇关于将自定义 javascript 事件绑定到 angular的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!