Wes*_*Yee 3 angularjs jquery-draggable angularjs-directive angularjs-scope
我很有棱角,所以请原谅我缺乏理解.
我有一个名为"draggable"的指令,我希望能够在控制器中跟踪它的x位置并对其执行一些逻辑.当用户将元素(一个简笔画)向右拖动时,额外的棒图应该直接出现在它后面.控制器应该知道x位置并根据它的位置,增加一个计数器,该计数器将决定可拖动元件后面出现多少个棒图.
此代码当前不起作用,因为控制器没有接收x的值.
我的指示:
app.directive('draggable', function() {
return {
restrict: 'A',
scope: "=x",
link: function (scope, element, attrs) {
$(element).draggable({
containment: "parent",
axis: "x",
drag: function(){
scope.x = $(this).offset().left;
}
});
}
};
});
Run Code Online (Sandbox Code Playgroud)
我的控制器:
app.controller("main-controller", function($scope) {
$scope.range = function(n) {
return new Array(figures);
};
$scope.$watch("x", function(){
console.log($scope.x);
figures = x / (stick_figure_height)
});
});
Run Code Online (Sandbox Code Playgroud)
我的HTML:
<div class="human-slider" ng-controller="main-controller">
<div draggable class="human-draggable">
<img src="images/stickfigure.png"/>
</div>
<div ng-repeat="i in range()">
<img src="images/stickfigure.png"/>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
控制器没有从draggable指令中获取x的更新值的原因是因为x的值正在更新的位置.X在一个转弯中更新,该转弯是在angularJS库(拖动事件处理程序)之外的方法中创建的.这个问题的解决方案是使用$ .apply来更新绑定.
更新的代码:
// Create our angular app
var app = angular.module('celgeneApp',[]);
// Main controller
app.controller("main-controller", function($scope) {
$scope.x = 0;
$scope.figures = 0;
$scope.range = function(n) {
return new Array($scope.figures);
};
$scope.$watch('x', function(){console.log($scope.x);});
});
// Draggable directive
app.directive('draggable', function() {
return {
restrict: 'A',
scope: false,
link: function (scope, element, attrs) {
$(element).draggable({
containment: "parent",
axis: "x",
drag: function(){
// Need to use $apply since scope.x is updated
// in a turn outside a method in the AngularJS library.
scope.$apply(function(){scope.x = element.offset().left;});
}
});
}
};
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6268 次 |
最近记录: |