gpt4 book ai didi

javascript - 未调用 AngularJS 指令范围函数

转载 作者:行者123 更新时间:2023-11-30 00:13:17 25 4
gpt4 key购买 nike

我创建了以下指令:

app.directive("autoLoad", function ($window) {
return {
scope: {
do: '&'
},
link : function(scope, element, attrs) {
var scroller = element[0];
angular.element($window).bind("scroll", function() {
if(($(window).scrollTop() + $(window).height()) > ($(document).height() - 100)) {
console.log("GOT HERE!");
scope.do(); // LOAD POSTS
}
});
}
};
});

当用户滚动到页面底部时,该指令应调用 do 函数。这是使用指令的 div:

<body ng-app="storeApp" layout="row" ng-controller="MainCtrl" ng-cloak">
...
<div flex layout="column" tabIndex="-1" role="main"
class="md-whiteframe-z2" auto-Load do="doSomething()">

Controller 看起来像这样:

app.controller("HomeCtrl", function($scope, controllerManager) {
...

$scope.doSomething = function() {
console.log("PLEASE WORK!");
};
});

当我到达页面底部时,正在打印 GOT HERE,但从未显示第二条语句。为什么controller中的函数没有被调用?

编辑:我正在使用选项卡,每个选项卡都有不同的 Controller 。所以应用于 body 对象的主 Controller 实际上并没有 doSomething 函数在里面:

app.config(function($stateProvider, $urlRouterProvider) {
$stateProvider.state('home', {
url : "/home",
templateUrl : "main.html",
controller : 'HomeCtrl'
}).state('top', {
url : "/top",
templateUrl : "main.html",
controller : 'TopCtrl'
}).state('trending', {
url : "/trending",
templateUrl : "main.html",
controller : 'TrendingCtrl'
})
$urlRouterProvider.otherwise('/home');
});

app.controller("MainCtrl", function($scope, $location, $log) {
$scope.selectedIndex = 0;
$scope.$watch('selectedIndex', function(current, old) {
switch (current) {
case 0:
$location.url("/home");
break;
case 1:
$location.url("/top");
break;
case 2:
$location.url("/trending");
break;
}
});
});

do something 功能实际上是每个子 Controller 的一部分:HomeCtrl、TopCtrl 等。

问题似乎是范围是由 MainCtrl 定义的,而不是它当前所在的任何选项卡。如何改变?

最佳答案

首先,您确实需要为此使用服务或工厂,但如果您仍想使用表达式绑定(bind),请将代码从链接函数移至指令 Controller (参见 jsbin https://jsbin.com/nohotizefi/edit?html,js,output)

 app.directive("autoLoad", function ($window) {
return {
scope: {
do: '&'
},
controller : function($scope, $element) {
var scroller = $element;
angular.element($window).bind("scroll", function() {
if(($(window).scrollTop() + $(window).height()) > ($(document).height() - 100)) {
console.log("GOT HERE!");
$scope.do(); // LOAD POSTS
}
});
}
};

});

关于javascript - 未调用 AngularJS 指令范围函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35628403/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com