【发布时间】:2015-03-20 06:27:22
【问题描述】:
所以,我在隔离指令的范围时遇到了问题。在我隔离作用域之前,它工作正常,从父作用域中提取从工厂获取数据的函数。该指令将是一个滑块,它需要能够在页面上有多个实例。出于这个原因,我需要隔离范围。我尝试了一些不同的东西,但没有任何效果,所以我猜我还有其他问题。这是我的代码的 sn-ps。 预先感谢您的帮助。 :)
编辑添加: 范围现在已成功隔离,但功能似乎没有。当指令有多个实例时,函数会影响每个实例,而不仅仅是一个实例。
控制器:
//
function BaseController ($scope, dataFactory) {
$scope.getMedia = function () {
dataFactory.getMedia()
.success(function (data) {
console.log(data);
$scope.sliderItems = data.Items;
$scope.topItems = [];
$scope.bottomItems = [];
// divide results of sliderItems into 2 rows
// this ensures that first item from EACH ROW disappears
for (var i=0; i < $scope.sliderItems.length; i++){
if ((i+2)%2==0) {
$scope.topItems.push( $scope.sliderItems[i]);
}
else {
$scope.bottomItems.push( $scope.sliderItems[i]);
}
}
})
.error(function (error) {
$scope.status = 'Unable to load ' + error.message;
});
}
}angular
.module('bellApp')
.controller('BaseController', BaseController);
//
指令:
function singleSlider() {
return {
// default is A, no need to asign
templateUrl: 'views/single-slider.html',
scope: {
slideritems :'='
},
link: function (scope) {
scope.displayInfo = function (item) {
scope.itemDetail = item;
scope.box = true;
};
scope.close = function () {
scope.box = false;
};
scope.sSlide = function () {
//set the appropriate direction
scope.direction = 1;
var slider = scope.slideritems;
//remove first item from slider
var shift = slider.shift();
//send removed item to end of slider array
slider = slider.push(shift);
};
scope.sSlideBack = function () {
//set the appropriate direction
scope.direction = 0;
var slider = scope.slideritems;
//remove last item from slider
var pop = slider.pop();
//send to front of array
slider = slider.splice(0,0,pop);
};
}
};
}angular
.module('bellApp')
.directive('singleSlider', singleSlider);
查看:
...
<body ng-app="bellApp" ng-controller="BaseController">
<div single-slider media="getMedia()" class="media-slider"></div>
...
【问题讨论】:
-
你能创建一个 plunker 吗?什么不工作?
-
您正在调用 getMedia。它应该是 '' 另一方面,我没有看到指令链接函数中的任何函数调用。跨度>
-
如果你只需要数据,不要传递函数。在控制器中调用你的函数 $scope.getMedia();并将结果你需要的 $scope.sliderItems , $scope.topItems , $scope.bottomItems 传递给隔离指令
-
$scope.getMedia 没有返回语句 - 这不是指令的问题吗?
-
@micha 我试过调用并且也只是使用 media=getMedia。两者都没有奏效。你能举个例子说明我将如何传递这些结果范围吗?
标签: javascript angularjs scope directive