[英]Angular.js — Directive to controller communication
我很有棱角,所以請原諒我缺乏理解。
我有一個名為“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;
}
});
}
};
});
我的控制器:
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)
});
});
我的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>
控制器沒有從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;});
}
});
}
};
});
檢查我的這個父控制器和指令如何通信:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.