AngularJS Simple Signature Pad Directive (without jQuery) - angularjs

With the help of stackoverflow i got me a simple canvas signature directive. The problem is that it works with mouse events (mousedown, mouseup, mousemove) but is not working with touch events (touchstart,touchmove,touchend). I have ngTouch in my main app module and in the module that holds the directive. I hope you can help me. Here's the code:
var sig = angular.module('signature', ['ngTouch']);
sig.directive("mjav", ['$document', function ($document) {
return {
restrict: "A",
link: function (scope, element) {
var ctx = element[0].getContext('2d');
ctx.canvas.width = window.innerWidth - 20;
var tempCanvas = document.createElement('nanavas');
// variable that decides if something should be drawn on mousemove
var drawing = false;
// the last coordinates before the current move
var lastX;
var lastY;
element.on('touchstart', function (event) {
if (event.offsetX !== undefined) {
lastX = event.offsetX;
lastY = event.offsetY;
} else {
lastX = event.layerX - event.currentTarget.offsetLeft;
lastY = event.layerY - event.currentTarget.offsetTop;
}
// begins new line
ctx.beginPath();
drawing = true;
});
element.on('touchmove', function (event) {
if (drawing) {
// get current mouse position
if (event.offsetX !== undefined) {
currentX = event.offsetX;
currentY = event.offsetY;
} else {
currentX = event.layerX - event.currentTarget.offsetLeft;
currentY = event.layerY - event.currentTarget.offsetTop;
}
draw(lastX, lastY, currentX, currentY);
// set current coordinates to last one
lastX = currentX;
lastY = currentY;
}
});
$document.on('touchend', function (event) {
// stop drawing
drawing = false;
});
// canvas reset
function reset() {
element[0].width = element[0].width;
}
function draw(lX, lY, cX, cY) {
// line from
ctx.moveTo(lX, lY);
// to
ctx.lineTo(cX, cY);
// color
ctx.strokeStyle = "#000";
// draw it
ctx.stroke();
}
}
};
}]);

If someone will need a simple signature directive for AngularJS this is what I came up with in the end:
var sig = angular.module('signature', []);
sig.controller('signatureCtrl', ['$scope', function ($scope) {
$scope.clearVal = 0;
$scope.saveVal = 0;
$scope.clear = function () {
$scope.clearVal += 1; //On this value change directive clears the context
}
$scope.saveToImage = function () {
$scope.saveVal = 1; //On this value change directive saves the signature
}
}]);
sig.directive("signatureDir", ['$document', '$log', '$rootScope', function ($document, $log, $rootScope) {
return {
restrict: "A",
link: function (scope, element, attrs) {
var ctx = element[0].getContext('2d');
ctx.canvas.width = window.innerWidth - 30;
// the last coordinates before the current move
var lastPt;
function getOffset(obj) {
return { left: 15, top: 116 }; //Got a fixed offset
}
attrs.$observe("value", function (newValue) {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
});
attrs.$observe("saveVal", function (newValue, dnid) {
var imagedata = ctx.canvas.toDataURL();
$rootScope.signatureTemp.push({'dnid':dnid, 'signature':imagedata});
});
element.on('touchstart', function (e) {
e.preventDefault();
ctx.fillRect(e.touches[0].pageX - getOffset(element).left, e.touches[0].pageY - getOffset(element).top, 2, 2);
lastPt = { x: e.touches[0].pageX - getOffset(element).left, y: e.touches[0].pageY - getOffset(element).top };
});
element.on('touchmove', function (e) {
e.preventDefault();
if (lastPt != null) {
ctx.beginPath();
ctx.moveTo(lastPt.x, lastPt.y);
ctx.lineTo(e.touches[0].pageX - getOffset(element).left, e.touches[0].pageY - getOffset(element).top);
ctx.stroke();
}
lastPt = { x: e.touches[0].pageX - getOffset(element).left, y: e.touches[0].pageY - getOffset(element).top };
});
element.on('touchend', function (e) {
e.preventDefault();
lastPt = null;
});
}
};
}]);
Markup:
<div ng-controller="signatureCtrl">
<ul class="list-group">
<h3 style="padding-left: 15px;">Signature</h3>
<li class="list-group-item">
<canvas saveVal="{{ saveVal }}" value="{{ clearVal }}" style="border: 1px solid black;" id="canvas1" width="200" height="200" signatureDir></canvas>
<button class="btn btn-warning" ng-click="clear()">Clear</button>
<button class="btn btn-primary" ng-click="ok()">Save</button>
</li>
</ul>
</div>
If anyone can see some bad code in here please correct me!

Related

Add focus/blur event in directive not working with templateUrl

I'm on a mysterious bug since last friday and perhaps you have an explanation.
I have a directive define like that :
//------------------------------------------------------------------------------
// fl-main-menu
// Type: Element
// Description: Creates a...
//------------------------------------------------------------------------------
uiModule.directive('flNavMenu', ['$rootScope', function ($rootScope) {
//-------------------------
// CONTROLLER
//-------------------------
var componentController = function ($scope, $element, $state, localize, $stateParams, StateManager)
{
$scope.isMenuOpened = false;
$scope.buttonsData = [
{
name: "Games",
data: {
type: "navMenuIconButton",
label: "menu_Games",
imgUrl: "./images/ic-controller-w.svg",
imgUrlOver: "./images/ic-controller-w.svg",
cb: function () { StateManager.display("gameCategories"); }
}
},
{
name: "News",
data: {
type: "navMenuIconButton",
label: "News",
imgUrl: "./images/ic-news-w.svg",
imgUrlOver: "./images/ic-news-w.svg",
cb: function () { StateManager.display("newsList", { spaceId: '', newsIndex: 0}); }
}
}
];
var updateNavButtons = function (){
$scope.navButtons = [{
imgUrl: "./images/ic-menu-w.svg",
label: "Menu_Close"
}
];
if(app.fromGame){
$scope.navButtons.push({
imgUrl: "./images/navBar-ico-Y-w.svg",
label: "Btn_BackToGame"
}
);
}
};
updateNavButtons();
$scope.unregisterStageChange = $rootScope.$on('$stateChangeSuccess', function (event) {
var buttons: any = document.getElementsByClassName('fl-component navmenu-item-button');
var element : any;
if ($state.includes("newsList")) {
if (!$stateParams.spaceId)
element = buttons[2];
else
element = buttons[1];
}
else if ($state.includes("main")) {
element = buttons[0];
}
else {
element = buttons[1];
}
if (element) {
$element[0].children[0]._lastFocusElement = element;
$element[0].children[0]._focusables = buttons;
}
});
var fromGame = false;
$scope.app = app;
$scope.unwatchFromGame = $scope.$watch("app.fromGame", function (newValue, oldValue) {
if (newValue === fromGame) {
return;
}
updateNavButtons();
});
function openCloseMenu()
{
if ($element[0].style.display != 'none')
{
if ($rootScope.isVideoPlayerOpen)
{
$rootScope.$emit("closeVideo");
}
if (!$scope.isMenuOpened)
{
$scope.onViewOver();
}
else
{
$scope.onViewOut();
}
}
};
function isMenuButtonPressed(keyPressed)
{
var keyMapping = platform.getKeyMapping();
if ((platform.isPC() && keyPressed == keyMapping.Space)
|| (platform.isMobile()
&& keyPressed == keyMapping.Enter))
{
return true;
}
return false;
};
function onKeyUp(event)
{
if (isMenuButtonPressed(event.keyCode))
{
openCloseMenu();
}
};
EventManager.addEventListener(window.document.body, BaseEventType.KEYUP, BaseEventPhase.CAPTURE_PHASE, onKeyUp, this);
$scope.$on('$destroy', () => {
$scope.unwatchFromGame();
$scope.unregisterStageChange();
$element[0].children[0].onKeyDownEvent = undefined;
EventManager.removeEventListener(window.document.body, BaseEventType.KEYUP, BaseEventPhase.CAPTURE_PHASE, onKeyUp, this);
TweenMax.killTweensOf($element[0].children[0]);
TweenMax.killTweensOf($element[0].children[1]);
})
};
//-------------------------
// LINK
//-------------------------
var componentLink = function (scope, element)
{
var offset = 185;
var menu = element[0].children[0];
var tongue = element[0].children[1];
var wrapper = document.getElementById('wrapper');
/**
* Close the tongue and open the menu
*/
scope.onViewOver = function () {
var width = menu.scrollWidth;
TweenMax.killTweensOf(menu);
TweenMax.killTweensOf(tongue);
//Make the tongue disapear, and the menu appear
TweenMax.to(tongue, 0.2, { alpha: 0, ease: Quad.easeOut });
TweenMax.to(menu, 0.2, { alpha: 1, ease: Quad.easeIn });
//Open menu animation (css transition)
offset = $rootScope.app.isSnapMode ? 250 : 95;
if (wrapper) wrapper.style.left = ((width / 2) + offset) + 'px';
menu.style.left = '0px';
scope.isMenuOpened = true;
};
/**
* Close the menu and open the tongue
*/
scope.onViewOut = function () {
TweenMax.killTweensOf(menu);
TweenMax.killTweensOf(tongue);
//Make the menu disapear, and the tongue appear
TweenMax.to(tongue, 0.2, { alpha: 1.0, ease: Quad.easeIn });
TweenMax.to(menu, 0.1, { alpha: 0, ease: Expo.easeIn, delay:0.2});
//Close menu animation (css transition)
if (wrapper) wrapper.style.left = '0px';
menu.style.left = '-480px';
scope.isMenuOpened = false;
};
element[0].firstChild.onBlurEvent = scope.onViewOut;
element[0].firstChild.onFocusEvent = scope.onViewOver;
};
//-------------------------
// TEMPLATE
//-------------------------
var componentTemplate = '<div class="navmenu-wrapper">' +
'<div id="navmenu" class="fl-container navmenu navmenu-fixed-left fl-fixed-container">'+
'<div>'+
'<ul>' +
'<fl-nav-menu-item ng-repeat="buttonData in buttonsData" nav-item-data="buttonData" class="text - center" id="ID{{$index}}"></fl-nav-menu-item>' +
'</ul>'+
'<ul class="navmenu-nav-icons">' +
'<div ng-repeat="navButton in navButtons" class="navmenu-nav-icon">' +
'<img ng-src="{{navButton.imgUrl}}">' +
'<span>{{navButton.label | i18n }}</span>' +
'</div>' +
'</ul>'+
'</div>'+
'<div>'+
'</div>'+
'</div>'+
'<img src="./images/btn_drawer_menu.png" class="navmenu-tongue" id="navmenu-tongue">' +
'</div>';
//-------------------------
// RETURN
//-------------------------
return {
restrict: "E",
controller: ["$scope", "$element", '$state', 'localize', '$stateParams', 'UplayTracking', 'StateManager', componentController],
link: componentLink,
template: componentTemplate,
replace:true
}
}]);
You can see in the componentLink method that we had manually methods for onFocus/onBlur event:
element[0].firstChild.onBlurEvent = scope.onViewOut;
element[0].firstChild.onFocusEvent = scope.onViewOver;
The problem is : if I change the template of this directive for a templateUrl (so put all html in a separate file), when the onBlur/onFocus event are raised, our methods are not called. Do you have an idea why ? Thanks for your help !
-We use templateCache to loading our html template.
-I already verify if my element[0] is the same with ou without templateUrl and yes it's the same element.

Define and Watch a variable according to windowidth

I'm struggling creating a directive to assign and update a variable, that compares to the window width, and updates with resize.
I need the variable as compared to using CSS because I will work it into ng-if. What am I doing wrong? Here is the code:
var app = angular.module('miniapp', []);
function AppController($scope) {}
app.directive('widthCheck', function ($window) {
return function (scope, element, attr) {
var w = angular.element($window);
scope.$watch(function () {
return {
'w': window.innerWidth
};
}, function (newValue, oldValue, desktopPlus, isMobile) {
scope.windowWidth = newValue.w;
scope.desktopPlus = false;
scope.isMobile = false;
scope.widthCheck = function (windowWidth, desktopPlus) {
if (windowWidth > 1399) {
scope.desktopPlus = true;
}
else if (windowWidth < 769) {
scope.isMobile = true;
}
else {
scope.desktopPlus = false;
scope.isMoblie = false;
}
}
}, true);
w.bind('resize', function () {
scope.$apply();
});
}
});
JSfiddle here: http://jsfiddle.net/h8m4eaem/2/
As mentioned in this SO answer it's probably better to bind to the window resize event with-out watch. (Similar to Mr. Berg's answer.)
Something like in the demo below or in this fiddle should work.
var app = angular.module('miniapp', []);
function AppController($scope) {}
app.directive('widthCheck', function($window) {
return function(scope, element, attr) {
var width, detectFalse = {
desktopPlus: false,
isTablet: false,
isMobile: false
};
scope.windowWidth = $window.innerWidth;
checkSize(scope.windowWidth); // first run
//scope.desktopPlus = false;
//scope.isMoblie = false; // typo
//scope.isTablet = false;
//scope.isMobile = false;
function resetDetection() {
return angular.copy(detectFalse);
}
function checkSize(windowWidth) {
scope.detection = resetDetection();
if (windowWidth > 1000) { //1399) {
scope.detection.desktopPlus = true;
} else if (windowWidth > 600) {
scope.detection.isTablet = true;
} else {
scope.detection.isMobile = true;
}
}
angular.element($window).bind('resize', function() {
width = $window.innerWidth;
scope.windowWidth = width
checkSize(width);
// manuall $digest required as resize event
// is outside of angular
scope.$digest();
});
}
});
.fess {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="miniapp" ng-controller="AppController">
<div width-check class="fess" resize>
window.width: {{windowWidth}}
<br />desktop plus: {{detection.desktopPlus}}
<br />mobile: {{detection.isMobile}}
<br />tablet: {{detection.isTablet}}
<br/>
</div>
</div>
scope.widthCheck is assigned an anonymous function and RE-ASSIGNED that same function each time this watcher fires. I also notice it's never called.
you should move that piece out of the $watch and call the function when the watcher fires
There's no need for a watch, you're already binding to resize. Just move your logic in there. And as Jun Duan said you continously create the funciton. Here's the change:
app.directive('widthCheck', function ($window) {
return function (scope, element, attr) {
function widthCheck(windowWidth) {
if (windowWidth > 1399) {
scope.desktopPlus = true;
}
else if (windowWidth < 769) {
scope.isMobile = true;
}
else {
scope.desktopPlus = false;
scope.isMoblie = false;
}
}
windowSizeChanged();
angular.element($window).bind('resize', function () {
windowSizeChanged();
scope.$apply();
});
function windowSizeChanged(){
scope.windowWidth = $window.innerWidth;
scope.desktopPlus = false;
scope.isMobile = false;
widthCheck(scope.windowWidth);
}
}
});
jsFiddle: http://jsfiddle.net/eqd3zu0j/

Creating a directive for window resizing

I have four mostly square looking charts which I need to resize on window resize. I have created a directive as below inside my angular controller at the top. This doesn't seem to work as the directive seem to executing as soon as the page loads and nothing seems to happen on resize. What am I missing here?
targetApp.directive('rsz', function ($window) {
return function (scope, element) {
var w = angular.element($window),
iw = w.innerWidth,
ih = w.innerHeight;
//resizing relative to the this parent container
scatterParentDimensions = getoffsetDimensions('#scatter-container'),
expectedWidth, expectedHeight;
console.log('rel w:', scatterParentDimensions.width, 'rel h:', scatterParentDimensions.height);
if (iw > ih) {
expectedWidth = scatterParentDimensions.width / 2;
expectedHeight = (scatterParentDimensions.height < iw)
? scatterParentDimensions.height / 2
: scatterParentDimensions.height / 4;
}
else {
expectedWidth = iw / 2;
expectedHeight = ih - 50;
}
// this is returning NaN as soon as the page is loaded.
console.log('set w:', expectedWidth, 'set h:', expectedHeight);
var selector = "#" + element.id;
if ($(selector).highcharts()) {
chart = $(selector).highcharts();
chart.setSize(expectedWidth, expectedHeight, false);
}
w.bind('resize', function () {
scope.$apply();
});
}
})
I have added the directive rsz on the four charts that need resizing.
//scatter.html
<div id="target-charts">
<div id="scatter-container" class="col-sm-8">
<div class="row">
<div class="col-sm-6">
<div class="scatter-chart">
<div class="chart-body" rsz id="scatterA"></div>
</div>
</div>
<div class="col-sm-6">
<div class="scatter-chart">
<div class="chart-body" rsz id="scatterB"></div>
</div>
</div>
<div class="col-sm-6">
<div class="scatter-chart">
<div class="chart-body" rsz id="scatterC"></div>
</div>
</div>
<div class="col-sm-6">
<div class="scatter-chart">
<div class="chart-body" rsz id="scatterD"></div>
</div>
</div>
</div>
</div>
</div>
Definition for getOffsetDimensions
function getoffsetDimensions(selector) {
var el = document.querySelector(selector);
return {
width: el.offsetWidth,
height: el.offsetHeight
}
}
in your directive, you listen to the resize event but didn't do anything (scope.$apply basically does nothing here).
you can either do the actually resizing inside of event handler, for example
myapp.directive('resize1', function($window) {
return function(scope, element, attr) {
var w = angular.element($window);
w.on('resize', function() {
var hh = document.getElementById('header').offsetHeight;
var fh = document.getElementById('footer').offsetHeight;
console.log('hh & fh', hh, fh);
var tp = hh + 2;
var bt = fh + 2;
console.log('tp & bt', tp, bt);
var changes = {
bottom: bt + 'px',
top: tp + 'px',
}
element.css(changes);
scope.$apply();
});
};
});
or watch the dimension changes, for example
app.directive('resize', function ($window) {
return function (scope, element) {
var w = angular.element($window);
scope.getWindowDimensions = function () {
return {
'h': w.height(),
'w': w.width()
};
};
scope.$watch(scope.getWindowDimensions, function (newValue, oldValue) {
scope.windowHeight = newValue.h;
scope.windowWidth = newValue.w;
scope.style = function () {
return {
'height': (newValue.h - 100) + 'px',
'width': (newValue.w - 100) + 'px'
};
};
}, true);
w.bind('resize', function () {
scope.$apply();
});
}
})
Eventually this is how I have made this work. It is still not the perfect solution and not at all generic, but I got it work for the initial stage of what I was looking for.
targetApp.directive('resize', function ($window) {
return function (scope, element, attr) {
var w = angular.element($window);
scope.$watch(function () {
return {
'h': window.innerHeight,
'w': window.innerWidth
};
}, function (newValue, oldValue) {
var ew, eh, scatterParentDimensions = getoffsetDimensions('#scatter-container');
if (newValue.w > newValue.h) {
ew = scatterParentDimensions.width / 2;
eh = (scatterParentDimensions.height < newValue.w)
? scatterParentDimensions.height / 2
: scatterParentDimensions.height / 4;
}
else {
ew = newValue.w / 2;
eh = newValue.h - 50;
}
//resize highcharts
var selector = '#' + element[0].id;
var chart = angular.element(selector).highcharts();
chart.setSize(ew, eh, false);
}, true);
w.bind('resize', function () {
scope.$apply();
});
}
});

Change Text in directive

How can I change something (for instance the color) in the directive?
I have a controller which gets after every 3 seconds new data (eye Positions)
myApp.controller('MainController', function ($scope, $interval, externalService, eyeTrackerService) {
$rootScope.gazePoints = [];
var size = 4;
var analyze = function () {
if ($rootScope.gazePoints.length > size) {
$scope.gazeArea = eyeTrackerService.getGazePoints($scope.gazePoints);
//reduce data in array
$scope.gazePoints.splice(0, 3);
}
};
var eyeTrackerData = function () {
externalService.getData().then(function (eyeTrackerData) {
var eyetracker = eyeTrackerData.data.EyeTracker;
var gaze_X = (eyetracker.X_left + eyetracker.X_right) * 0.5 * screen.availWidth;
var gaze_Y = (eyetracker.Y_left + eyetracker.Y_right) * 0.5 * screen.availHeight;
$scope.gazePoints.push({ x: gaze_X, y: gaze_Y });
analyze();
});
};
$interval(eyeTrackerData, 3000)
});
The service gets an array of gazePoints and have to analyse if the user is looking at the panel:
myApp.service('eyeTrackerService', function ($rootScope) {
this.getGazePoints = function (gazePoints) {
var counter = 0;
var date = $rootScope.rect;
for (var i = 0; i < gazePoints.length; i++) {
var x = gazePoints[i].x;
var y = gazePoints[i].y;
if (x >= date.left && x <= date.right && y >= date.top && y < date.bottom) {
counter =+ 1;
console.log("is watching");
if(counter == 5){
///Here it should call the directive and change the color
}
}
else {
console.log("is not watching")
}
}
}
});
my directive:
myApp.directive('dateInfo', function ($rootScope, $interval) {
return {
restrict: 'A',
scope: {
},
templateUrl: '123/Scripts/directives/html/dateInfo.html',
link: function (scope, element, attrs) {
$interval(function () {
$rootScope.rect = element[0].getBoundingClientRect();
//Here i want to change the color
//for example a scope.changetext(); but how??
}, 3000);
}
};
});
my html-file:
<div class="panel panel-primary">
<div class="panel-heading">MyPanel</div>
<div class="panel-body">
<input id="test" name="test">
</div>
</div>
I know it´s a lot of code. But as you can see the directive are also called after every second to get the current position of the panel.
Now I want to change the color in the panel, after the counter is == 5
What is the best solution in that case? I heard it not good to change the text in the controller.
Inside the interval, use
$interval(function () {
$rootScope.rect = element[0].getBoundingClientRect();
element.addClass('someClassThatSetsColor');
}, 3000);
You can set the class based on a parameter of your choice, say if it's not looking you'll set a class that changes the color to red, or whatever.

AngularJS UI Bootstrap dismiss() won´t work

Let me start by saying that I am very new to angular.
I have tried to setup a modal ui which works fine. But when I click the "cancel" button on the interface nothing happens.
This is my code:
(function () {
var domainName = 'TournamentCategory';
angular.module('tournamentCategories').controller("CategoriesController",
['$scope', '$modal', 'guidGenerator', 'eventBus', domainName + "Service",
'TournamentCategoryModelFactory',
function ($scope, $modal, guidGenerator, eventBus, domainService, modelFactory)
{$scope.openTournamentTree = function () {
var modalInstance = $modal.open({
templateUrl: 'TournamentTreeModal.html',
controller: 'TreeController',
size: 'wide-90',
resolve: {
}
});
modalInstance.result.then(function (selectedItem) {
//$scope.selected = selectedItem;
}, function () {
//$log.info('Modal dismissed at: ' + new Date());
});
};
$scope.ok = function () {
modalInstance.close();
}
$scope.cancel = function () {
modalInstance.dismiss('cancel');
};
}]);
})();
The HTML:
<script type="text/ng-template" id="TournamentTreeModal.html">
<div class="modal-header">
</div>
<div class="modal-body">
<div class="include-tree" ng-include="'tournament-tree.html'"></div>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">GEM</button>
<button ng-click="cancel()" class="btn btn-warning" type="button" data-dismiss="modal">LUK, uden at gemme</button>
</div>
This is my "treeController"
angular.module('tournamentTree').controller("TreeController", ['$scope', 'guidGenerator', function ($scope, guidGenerator) {
$scope.allMatches = [];
$scope.finalMatch = [createNewMatch()];
$scope.tierCount = 1;
$scope.previousMatchTier = 0;
$scope.deletePreviousMatches = function (parentMatch) {
for (var i in parentMatch.previousMatches) {
var previousMatch = parentMatch.previousMatches[i];
_.remove($scope.allMatches, function (match) { return match.id == previousMatch.id });
}
parentMatch.previousMatches = [];
}
$scope.addMatches = function (thisMatch) {
if (thisMatch && !thisMatch.previousMatches)
thisMatch.previousMatches = [];
if (thisMatch && thisMatch.previousMatches.length == 0) {
thisMatch.previousMatches.push(createNewMatch(thisMatch));
thisMatch.previousMatches.push(createNewMatch(thisMatch));
}
}
$scope.addMatchTier = function () {
for (var i in $scope.allMatches) {
var match = $scope.allMatches[i];
if (match.previousMatches.length == 0) {
$scope.addMatches(match);
}
}
$scope.tierCount++;
}
$scope.previousMatchTier = function () {
for (var i in $scope.allMatches) {
var previous;
if (previous.allMatches.length == i) {
previous = $scope.allMatches[i] - $scope.allMatches[i - 1];
}
}
}
$scope.removeMatchTier = function () {
//if (confirm('Er du sikker på, at du vil slette det yderste niveau af turneringstræet?')) {
var matchesToDelete = [];
for (var i in $scope.allMatches) {
var match = $scope.allMatches[i];
if (match.previousMatches.length == 0) {
matchesToDelete.push(match.nextMatch);
//$scope.deletePreviousMatches(match.nextMatch);
}
}
for (var i in matchesToDelete) {
$scope.deletePreviousMatches(matchesToDelete[i]);
}
$scope.tierCount--;
//}
}
$scope.hasPreviousMatches = function (match) {
return match && match.previousMatches && match.previousMatches.length > 0;
}
$scope.moveWinnerToNextMatch = function (match, winnerName) {
match.nextMatch.setPlayerName(match.id, winnerName);
}
function createNewMatch(nextMatch) {
var newMatch = {};
newMatch.tier = nextMatch && nextMatch.tier ? nextMatch.tier + 1 : 1;
newMatch.id = guidGenerator.newGuid();
newMatch.player1 = "";
newMatch.player2 = "";
newMatch.nextMatch = nextMatch;
newMatch.previousMatches = [];
newMatch.setPlayerName = function(matchId, playerName) {
for (var i in newMatch.previousMatches)
{
if (newMatch.previousMatches[i].id == matchId)
{
if (i == 0)
newMatch.player1 = playerName;
else
newMatch.player2 = playerName;
}
}
}
$scope.allMatches.push(newMatch);
return newMatch;
}
}]);
$dismiss is already available on modal scope so in template raplace cancel() with $dimiss() http://angular-ui.github.io/bootstrap/#/modal
That needs to go in your modals controller 'TreeController'
angular.module('tournamentCategories').controller('TreeController', function($scope, $modalInstance) {
$scope.ok = function () {
modalInstance.close();
}
$scope.cancel = function () {
modalInstance.dismiss('cancel');
};
});
I have an example in this plunker

Resources