I have the directive. There is zoom on scroll image and also you can drag image. I need, that image by default always be on the center (div or screen) and image also should be on center when you zoommed of your mouse wheel. Generally, center of image always should be on a center of screen (and you can drag image as before).
var app = angular.module('app', []);
app.directive('myDraggable', ['$document', '$timeout', function($document, $timeout) {
return function(scope, element, attr) {
var startX = 0, startY = 0, x = 0, y = 0;
scope.updateX = 0;
scope.updatesize = 50;
// scope.topsize = 1;
function zoomController (zoomtype, updatesize) {
var default_scale = 50;
var zoomtype = zoomtype;
var updatesize = updatesize;
if (zoomtype == 1 && updatesize > 150) {
return updatesize;
} else if (zoomtype == 1 && updatesize < 150){
return updatesize = updatesize * 1.02;
} else if (zoomtype == 0 && updatesize > 20){
return updatesize = updatesize / 1.02;
} else {
return updatesize;
}
}
/* mouse wheel */
var doScroll = function (e) {
e = window.event || e;
var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
$timeout(function() {
if (delta == 1) {
scope.updatesize = zoomController(1, scope.updatesize);
} else {
scope.updatesize = zoomController(0, scope.updatesize);
}
}, 30);
e.preventDefault();
};
if (window.addEventListener) {
window.addEventListener("mousewheel", doScroll, false);
window.addEventListener("DOMMouseScroll", doScroll, false);
} else {
window.attachEvent("onmousewheel", doScroll);
}
/* mouse wheel */
scope.zoomInImage = function () {
scope.updatesize = zoomController(1, scope.updatesize);
}
scope.zoomOutImage = function () {
scope.updatesize = zoomController(0, scope.updatesize);
}
element.on('mousedown', function(event) {
// Prevent default dragging of selected content
event.preventDefault();
startX = event.pageX - x;
startY = event.pageY - y;
$document.on('mousemove', mousemove);
$document.on('mouseup', mouseup);
});
function mousemove(event) {
y = event.pageY - startY;
x = event.pageX - startX;
scope.updateX = x;
scope.updateY = y;
scope.$apply();
element.css({
top: y + 'px',
left: x + 'px'
});
}
function mouseup() {
$document.off('mousemove', mousemove);
$document.off('mouseup', mouseup);
}
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<img my-draggable src="http://www.singhsatya.com/wp-content/uploads/2014/06/hello_world.png" style="width:{{updatesize}}%; top:{{updateY}}px; left:{{updateX}}px; position:relative; cursor:pointer;">
</div>
Wrap the img in a canvas and use transform: scale to zoom in/out.
/* jshint -W117 */
var app = angular.module('app', []);
function zoomController(zoomtype, updatesize) {
if (zoomtype == 1 && updatesize > 550) {
return updatesize;
} else if (zoomtype === 1 && updatesize < 550) {
return updatesize * 1.09;
} else if (zoomtype === 0 && updatesize > 20) {
return updatesize / 1.09;
} else {
return updatesize;
}
}
app.directive('myDraggable', ['$document', '$timeout', function ($document, $timeout) {
return function (scope, element) {
var startX = 0,
startY = 0,
x = 0,
y = 0;
scope.updateX = 0;
scope.updatesize = 100;
/* mouse wheel */
var doScroll = function (e) {
e = window.event || e;
var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
$timeout(function () {
if (delta == 1) {
scope.updatesize = zoomController(1, scope.updatesize);
} else {
scope.updatesize = zoomController(0, scope.updatesize);
}
}, 30);
e.preventDefault();
};
if (window.addEventListener) {
window.addEventListener("mousewheel", doScroll, false);
window.addEventListener("DOMMouseScroll", doScroll, false);
} else {
window.attachEvent("onmousewheel", doScroll);
}
/* mouse wheel */
scope.zoomInImage = function () {
scope.updatesize = zoomController(1, scope.updatesize);
};
scope.zoomOutImage = function () {
scope.updatesize = zoomController(0, scope.updatesize);
};
element.on('mousedown', function (event) {
// Prevent default dragging of selected content
event.preventDefault();
startX = event.pageX - x;
startY = event.pageY - y;
$document.on('mousemove', mousemove);
$document.on('mouseup', mouseup);
});
function mousemove(event) {
y = event.pageY - startY;
x = event.pageX - startX;
scope.updateX = x;
scope.updateY = y;
scope.$apply();
element.css({
top: y + 'px',
left: x + 'px'
});
}
function mouseup() {
$document.off('mousemove', mousemove);
$document.off('mouseup', mouseup);
}
};
}]);
.my-canvas {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
.my-canvas > img {
position:relative;
cursor:pointer;
transition: 0.25s transform;
}
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#*" data-semver="1.4.0-beta.6" src="https://code.angularjs.org/1.4.0-beta.6/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-app="app">
<div class="my-canvas">
<img my-draggable
src="http://www.singhsatya.com/wp-content/uploads/2014/06/hello_world.png"
style="transform: scale({{updatesize / 100}}); top:{{updateY}}px; left:{{updateX}}px;">
</div>
</div>
</body>
</html>
Related
I have this function type() where I define an array texts and I add some values to it and then I set the local texts array to the state array, so it'll be accessible for other functions as well.
var texts = [];
texts.push("Hello", 20, 20)
this.setState({texts: texts})
And this is the state:
state ={
texts:[]
}
I check with the alert() what's the index of 0 of the array to see if it's working, however it says it's undefined:
alert(this.state.texts[0])
This is my whole function:
type()
{
var canvas = document.getElementById('board'),
ctx = canvas.getContext('2d'),
font = '20px sans-serif',
hasInput = false;
var sketch = document.querySelector('#sketch');
var sketch_style = getComputedStyle(sketch);
canvas.width = parseInt(sketch_style.getPropertyValue('width'));
canvas.height = parseInt(sketch_style.getPropertyValue('height'));
var texts = [];
texts.push("Hello", 20, 20)
this.setState({texts: texts})
alert(this.state.texts[0])
ctx.font = font
ctx.fillText("rrwerwewewrewrwerwe", 50, 50)
canvas.onclick = function(e) {
if (hasInput) return;
addInput(e.clientX, e.clientY);
}
//Function to dynamically add an input box:
function addInput(x, y) {
var input = document.createElement('input');
input.type = 'text';
input.style.position = 'fixed';
input.style.left = (x - 4) + 'px';
input.style.top = (y - 4) + 'px';
input.onkeydown = handleEnter;
document.body.appendChild(input);
input.focus();
hasInput = true;
}
//Key handler for input box:
function handleEnter(e) {
var keyCode = e.keyCode;
if (keyCode === 13) {
addText(this.value, parseInt(this.style.left, 10), parseInt(this.style.top, 10));
document.body.removeChild(this);
hasInput = false;
}
}
//Draw the text onto canvas:
function addText(text, x, y) {
ctx.position = 'absolute';
ctx.font = font;
ctx.fillText(text, x, y);
}
}
I believe my react code is trying to access a server directory after its compiled and sent to the client. This means when it looks for the gameLogic.js and style.css files it cant locate them. I'm wondering how I would go about getting the react component im working on to get a copy of them and send them off to the remote client. I get the following errors.
pages/game.js
import * as React from "react";
import Layout from "../components/Layout";
import Separator from "../components/Separator";
import CanvasCanvas from "../components/CanvasCanvas";
export default class extends React.Component {
render() {
return (
<Layout>
<main>
<div className="loginBox5">
<Separator height={50}/>
<div className="center">
<h1>Game Play:</h1>
<Separator height={50}/>
<div id="PlayAreaImg" className="gameContainer">
<CanvasCanvas id={"Memes"}/>
</div>
</div>
<Separator height={350}/>
</div>
</main>
</Layout>
)
}
}
src/gameLogic.js
var keyState = {};
window.addEventListener('keydown',function(e){
keyState[e.keyCode || e.which] = true;
},true);
window.addEventListener('keyup',function(e){
keyState[e.keyCode || e.which] = false;
},true);
x = 100;
function drawObj(ctx, object){
var x = object[0];
var y = object[1];
var wid = object[2];
var hei = object[3];
var r = object[4];
var g = object[5];
var b = object[6];
var t = object[7];
// Renderer usage: Canvas context, x position, y position, object height, object width, red, green, blue, transparency
ctx.fillStyle = "rgba("+String(r)+","+String(g)+","+String(b)+","+String(t)+")"; // colour ball
ctx.fillRect (x, y, wid, hei); // render ball
return ctx;
}
function renderAll(objects){
console.log("### - Render: Starting - ###");
for (var i = 0; i < objects.length; i++) {
// Iterate over numeric indexes from 0 to 5, as everyone expects.
}
console.log("### - Render: Complete - ###");
}
//Define generic move function
function transformR(object, moveAmount, canvasHeight, canvasWidth){
if (keyState[37]){
object[0] -= moveAmount
// console.log("left");
}
if (keyState[38]){
object[1] -= moveAmount
if (object[1] < 0){
// console.log("Top Edge")
object[1] = 0;
}
// console.log("up");
}
if (keyState[39]){
object[0] += moveAmount
// console.log("right");
}
if (keyState[40]){
object[1] += moveAmount
if (object[1] > (canvasHeight-object[3])){
// console.log("Bottom Edge")
object[1] = canvasHeight-object[3];
}
// console.log("down");
}
return object;
}
function transformL(object, moveAmount, canvasHeight, canvasWidth){
if (keyState[65]){
object[0] -= moveAmount
// console.log("left");
}
if (keyState[87]){
object[1] -= moveAmount
if (object[1] < 0){
// console.log("Top Edge")
object[1] = 0;
}
// console.log("up");
}
if (keyState[68]){
object[0] += moveAmount
// console.log("right");
}
if (keyState[83]){
object[1] += moveAmount
if (object[1] > (canvasHeight-object[3])){
// console.log("Bottom Edge")
object[1] = canvasHeight-object[3];
}
// console.log("down");
}
return object;
}
function collisonDetect(ball, paddle){
if (ball[0] < paddle[0] + paddle[2] &&
ball[0] + ball[2] > paddle[0] &&
ball[1] < paddle[1] + paddle[3] &&
ball[3] + ball[1] > paddle[1]) {
ball[8] = -ball[8];
ball[9] = -ball[9];
console.log("inside");
} else {
// console.log("not touching/inside");
}
return ball;
}
function ballMotion(height, width, ball, rightPaddle, leftPaddle){
var x = ball[0];
var y = ball[1];
// collision detection
ball = collisonDetect(ball, leftPaddle);
ball = collisonDetect(ball, rightPaddle);
var xSpeed = ball[8];
var ySpeed = ball[9];
x += xSpeed;
y += ySpeed;
// sides collison detection
if (y <= 0){
y = 0;
ySpeed = -ySpeed;
}
if (y >= height-ball[2]) {
y = height-ball[2];
ySpeed = -ySpeed;
}
if (x <= 0) {
x = 0;
xSpeed = -xSpeed;
leftPoints +=1
}
if (x >= width-ball[3]) {
x = width-ball[3];
xSpeed = -xSpeed;
rightPoints +=1
}
// assign new values
ball[0] = x;
ball[1] = y;
ball[8] = xSpeed;
ball[9] = ySpeed;
return ball;
}
function onPositionUpdate(position){
var lat = position.coords.latitude;
var lng = position.coords.longitude;
console.log("Current position: " + lat + " " + lng);
}
function onDown(event){
cx = event.pageX;
cy = event.pageY;
console.log(cx, cy)
}
// Define objects as follows
// Renderer usage: Canvas context, x position, y position, object height, object width, red, green, blue, transparency
// Cut down usage: X, Y, height, width, red, green, blue, transparency
if (window.innerWidth < window.innerHeight) {
ballDim = [window.innerWidth*.02, window.innerWidth*.02]
} else {
ballDim = [window.innerHeight*.02, window.innerHeight*.02]
}
var ball = [window.innerWidth/2-((window.innerWidth*.02)/2), window.innerHeight*.8*.5-((window.innerHeight*.08)/2), ballDim[0], ballDim[1],200 ,200 ,200 ,3 , 3, 2];
var leftPaddle = [window.innerWidth*.01, window.innerHeight*.8*.5-((window.innerHeight*.08)/2), window.innerWidth*.01, window.innerHeight*.08, 0, 0, 200, 3];
var rightPaddle = [window.innerWidth*.8-(window.innerWidth*.01)-(window.innerWidth*.01), window.innerHeight*.8*.5-((window.innerHeight*.08)/2), window.innerWidth*.01, window.innerHeight*.08, 255, 100, 0, 3];
var leftPoints = 0;
var rightPoints = 0;
// Define gameLoop
function gameLoop(x,y) {
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(onPositionUpdate);
} else {
console.log("navigator.geolocation is not available");
}
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
canvas.addEventListener("mousedown",onDown,false);
var width = window.innerWidth*.8;
var height = window.innerHeight*.8
ctx.canvas.width = width;
ctx.canvas.height = height;
var moveAmount = 3;
var motionTicker = + new Date()
// console.log(motionTicker)
// move checking function
leftPaddle[0] = window.innerWidth*.01;
rightPaddle[0] = window.innerWidth*.8-(window.innerWidth*.01)-(window.innerWidth*.01);
leftPaddle = transformL(leftPaddle, moveAmount, height, width);
rightPaddle = transformR(rightPaddle, moveAmount, height, width);
ball = ballMotion(height, width, ball, rightPaddle, leftPaddle);
ctx.save();
ctx.clearRect(0,0,width,height);
// Render objects in frame
drawObj(ctx, ball);
drawObj(ctx, leftPaddle);
drawObj(ctx, rightPaddle);
ctx.font = String(window.innerWidth*.05)+"px Arial";
ctx.fillStyle = "white";
ctx.fillText(String(rightPoints)+" - "+String(leftPoints), window.innerWidth*.333, window.innerHeight*.1);
ctx.restore();
setTimeout(gameLoop, 1);
await this.forceUpdate();
this.state = {motionTicker}
}
/components/CanvasCanvas.js
import * as React from "react";
export default class extends React.Component {
render() {
return (
<canvas ref={"canvas"} id = {"canvas"} width={640} height={425}/>
)
}
async componentDidMount() {
const script = document.createElement("script");
console.log("ln14")
script.src = "../src/gameLogic.js";
script.async = true;
// console.log(script);
document.head.appendChild(script);
console.log(script);
await this.setState(
{
text: this.props.text,
...this.state
}
);
await this.forceUpdate();
const canvas = this.refs.canvas;
const ctx = canvas.getContext("2d");
ctx.fillText((this.state && this.state.text) ? this.state.text : "Not initialised (nullcheck)", 210, 75);
}
}
Expected result is the gameLogic js file will render its output inside the canvas element and forceUpdate it at the end of each 'frame'.
And the actual result is a string of 404's as follows:
http://localhost:3000/css/style.css net::ERR_ABORTED 404 (Not Found)
index.js:1 Warning: Extra attributes from the server: deluminate_imagetype
GET http://localhost:3000/src/gameLogic.js net::ERR_ABORTED 404 (Not Found)
Thanks for any help you can give in advance.
If you want to access these files after compilation put them inside the static folder for example script.src = "/static/gameLogic.js"
Or use dynamic import
import dynamic from 'next/dynamic'
const gameLogic = dynamic(() => import(`../src/gameLogic.js`))
dynamic-import doc
I used the ng-repeat in the ion-slide and operated the array myTags in the controller,ion-slide-tab-label was custom directive.When I changed the array,ng-repeat view has not changed.If I use the method remove() and then add() the same tag,it would be error:duplicate. Here's the code.
slidingTabsDirective.js
var slidingTabsDirective = angular.module("ionic").directive('ionSlideTabs', ['$timeout', '$compile', '$interval', '$ionicSlideBoxDelegate', '$ionicScrollDelegate', '$ionicGesture', function($timeout, $compile, $interval, $ionicSlideBoxDelegate, $ionicScrollDelegate, $ionicGesture) {
return {
require: "^ionSlideBox",
restrict: 'A',
link: function(scope, element, attrs, parent) {
var ionicSlideBoxDelegate;
var ionicScrollDelegate;
var ionicScrollDelegateID;
var slideTabs;
var indicator;
var slider;
var tabsBar;
var options = {
"slideTabsScrollable": true
};
var init = function() {
if (angular.isDefined(attrs.slideTabsScrollable) && attrs.slideTabsScrollable == false) {
options.slideTabsScrollable = false;
}
var tabItems = '<li ng-repeat="(key, value) in tabs" ng-click="onTabTabbed($event, {{key}})" class="slider-slide-tab" ng-bind-html="value"></li>';
if (options.slideTabsScrollable) {
//alert(options.slideTabsScrollable)
ionicScrollDelegateID = "ion-slide-tabs-handle-" + Math.floor((Math.random() * 10000) + 1);
tabsBar = angular.element('<ion-scroll delegate-handle="' + ionicScrollDelegateID + '" class="slidingTabs" direction="x" scrollbar-x="false"><ul>' + tabItems + '</ul> <div class="tab-indicator-wrapper"><div class="tab-indicator"></div></div> </ion-scroll>');
} else {
tabsBar = angular.element('<div class="slidingTabs"><ul>' + tabItems + '</ul> <div class="tab-indicator-wrapper"><div class="tab-indicator"></div></div> </div>');
}
slider = angular.element(element);
var compiled = $compile(tabsBar);
slider.parent().prepend(tabsBar);
compiled(scope);
//get Tabs DOM Elements
indicator = angular.element(tabsBar[0].querySelector(".tab-indicator"));
//get the slideBoxHandle
var slideHandle = slider.attr('delegate-handle');
var scrollHandle = tabsBar.attr('delegate-handle');
ionicSlideBoxDelegate = $ionicSlideBoxDelegate;
if (slideHandle) {
ionicSlideBoxDelegate = ionicSlideBoxDelegate.$getByHandle(slideHandle);
}
if (options.slideTabsScrollable) {
ionicScrollDelegate = $ionicScrollDelegate;
if (scrollHandle) {
ionicScrollDelegate = ionicScrollDelegate.$getByHandle(scrollHandle);
}
}
addEvents();
setTabBarWidth();
slideToCurrentPosition();
};
var addEvents = function() {
ionic.onGesture("dragleft", scope.onSlideMove, slider[0]);
ionic.onGesture("dragright", scope.onSlideMove, slider[0]);
ionic.onGesture("release", scope.onSlideChange, slider[0]);
};
var setTabBarWidth = function() {
if (!angular.isDefined(slideTabs) || slideTabs.length == 0) {
return false;
}
tabsList = tabsBar.find("ul");
var tabsWidth = 0;
angular.forEach(slideTabs, function(currentElement, index) {
var currentLi = angular.element(currentElement);
tabsWidth += currentLi[0].offsetWidth;
});
if (options.slideTabsScrollable) {
angular.element(tabsBar[0].querySelector(".scroll")).css("width", tabsWidth + 1 + "px");
} else {
slideTabs.css("width", tabsList[0].offsetWidth / slideTabs.length + "px");
}
slideToCurrentPosition();
};
var slideToCurrentPosition = function() {
if (!angular.isDefined(slideTabs) || slideTabs.length == 0) {
return false;
}
var targetSlideIndex = ionicSlideBoxDelegate.currentIndex();
var targetTab = angular.element(slideTabs[targetSlideIndex]);
var targetLeftOffset = targetTab.prop("offsetLeft");
var targetWidth = targetTab[0].offsetWidth;
indicator.css({
"-webkit-transition-duration": "300ms",
"-webkit-transform": "translate(" + targetLeftOffset + "px,0px)",
"width": targetWidth + "px"
});
if (options.slideTabsScrollable && ionicScrollDelegate) {
var scrollOffset = 40;
ionicScrollDelegate.scrollTo(targetLeftOffset - scrollOffset, 0, true);
}
slideTabs.removeClass("tab-active");
targetTab.addClass("tab-active");
};
var setIndicatorPosition = function(currentSlideIndex, targetSlideIndex, position, slideDirection) {
var targetTab = angular.element(slideTabs[targetSlideIndex]);
var currentTab = angular.element(slideTabs[currentSlideIndex]);
var targetLeftOffset = targetTab.prop("offsetLeft");
var currentLeftOffset = currentTab.prop("offsetLeft");
var offsetLeftDiff = Math.abs(targetLeftOffset - currentLeftOffset);
if (currentSlideIndex == 0 && targetSlideIndex == ionicSlideBoxDelegate.slidesCount() - 1 && slideDirection == "right" ||
targetSlideIndex == 0 && currentSlideIndex == ionicSlideBoxDelegate.slidesCount() - 1 && slideDirection == "left") {
return;
}
var targetWidth = targetTab[0].offsetWidth;
var currentWidth = currentTab[0].offsetWidth;
var widthDiff = targetWidth - currentWidth;
var indicatorPos = 0;
var indicatorWidth = 0;
if (currentSlideIndex > targetSlideIndex) {
indicatorPos = targetLeftOffset - (offsetLeftDiff * (position - 1));
indicatorWidth = targetWidth - ((widthDiff * (1 - position)));
} else if (targetSlideIndex > currentSlideIndex) {
indicatorPos = targetLeftOffset + (offsetLeftDiff * (position - 1));
indicatorWidth = targetWidth + ((widthDiff * (position - 1)));
}
indicator.css({
"-webkit-transition-duration": "0ms",
"-webkit-transform": "translate(" + indicatorPos + "px,0px)",
"width": indicatorWidth + "px"
});
if (options.slideTabsScrollable && ionicScrollDelegate) {
var scrollOffset = 40;
ionicScrollDelegate.scrollTo(indicatorPos - scrollOffset, 0, false);
}
};
scope.onTabTabbed = function(event, index) {
ionicSlideBoxDelegate.slide(index);
slideToCurrentPosition();
};
scope.tabs = [];
scope.addTabContent = function($content) {
$content = $content.replace(/\“/g, '').replace(/\”/g, '');
scope.tabs.push($content);
scope.$apply();
$timeout(function() {
slideTabs = angular.element(tabsBar[0].querySelector("ul").querySelectorAll(".slider-slide-tab"));
slideToCurrentPosition();
setTabBarWidth();
});
};
scope.onSlideChange = function(slideIndex) {
slideToCurrentPosition();
};
scope.onSlideMove = function() {
var scrollDiv = slider[0].getElementsByClassName("slider-slide");
var currentSlideIndex = ionicSlideBoxDelegate.currentIndex();
var currentSlide = angular.element(scrollDiv[currentSlideIndex]);
var currentSlideLeftOffset = currentSlide.css('-webkit-transform').replace(/[^0-9\-.,]/g, '').split(',')[0];
var targetSlideIndex = (currentSlideIndex + 1) % scrollDiv.length;
if (currentSlideLeftOffset > slider.prop("offsetLeft")) {
targetSlideIndex = currentSlideIndex - 1;
if (targetSlideIndex < 0) {
targetSlideIndex = scrollDiv.length - 1;
}
}
var targetSlide = angular.element(scrollDiv[targetSlideIndex]);
var position = currentSlideLeftOffset / slider[0].offsetWidth;
var slideDirection = position > 0 ? "right" : "left";
position = Math.abs(position);
setIndicatorPosition(currentSlideIndex, targetSlideIndex, position, slideDirection);
};
init();
},
controller: ['$scope', function($scope) {
this.addTab = function($content) {
$timeout(function() {
if ($scope.addTabContent) {
$scope.addTabContent($content);
}
});
};
}]
};
}]);
slidingTabsDirective.directive('ionSlideTabLabel', [function() {
return {
require: "^ionSlideTabs",
link: function($scope, $element, $attrs, $parent) {
$parent.addTab($attrs.ionSlideTabLabel);
}
};
}]);
index.html
<ion-slide-box id="slide_box" show-pager="false" ion-slide-tabs>
<ion-slide ng-repeat="tag in myTags track by $index" ion-slide-tab-label=“{{tag.tagname}}”>
.........
</ion-slide>
</ion-slide-box>
service.js
function getTags() {
var url = xxxxxxx;
return $http({
method: 'GET',
url: url
})
.success(function(res) {
//console.log('is collect success');
})
.error(function(msg, code) {
console.log('tag error.....', code);
});
}
indexCtrl.js
$scope.tags = [];
$scope.myTags = [];
$scope.moreTags = [];
function getTags() {
ds.getTags()
.then(function(res) {
var traTags = [];
var l = res.data.length;
$scope.tags = res.data;
traTags = angular.copy($scope.tags);
$scope.myTags = traTags.splice(0, l / 2);
$scope.moreTags = traTags;
});
}
function remove(index) {
if (!$scope.lock) {
$scope.moreTags.unshift($scope.myTags[index]);
$scope.myTags.splice(index, 1);
} else {
return;
}
}
function add(index) {
$scope.myTags.push($scope.moreTags[index]);
$scope.moreTags.splice(index, 1);
}
what should I do? please help me! Thank you!
function:
function addlist(obj, item, addtype) {
var isdata = false;
for (var i = 0; i < obj.length; i++) {
if (obj[i] == item) {
isdata = true;
break;
}
}
if (!isdata) {
if (addtype) {
obj.push(item);
} else {
obj.unshift(item);
}
}
}
code:
function remove(index) {
if (!$scope.lock) {
addlist($scope.moreTags,$scope.myTags[index],false);
$scope.myTags.splice(index, 1);
} else {
return;
}
}
function add(index) {
addlist($scope.myTags,$scope.moreTags[index],true);
$scope.moreTags.splice(index, 1);
}
I have created WordCloud from angularjs using wordCloud directive,
So whenever I change the input to the cloud after generating word cloud for the first time, I am unable form word cloud.
This issue is being, I am not able to refresh the directive.
Say my html and js is ,
var app = angular.module("myApp", ["tangcloud"]);
app.controller("myCtrl", function($scope) {
$scope.words = [
{id: 1, word: "oke", size: 1},
{id: 2, word: "blabla", size: 6},
{id: 3, word: "test", size: 7},
{id: 4, word: "schaap", size: 2},
{id: 5, word: "deployment", size: 10},
{id: 6, word: "woord3", size: 3},
{id: 7, word: "wogamalord4", size: 4}];
});
<tang-cloud words="words" on-click="test(word)"></tang-cloud>
Say my directive going to be
angular.module('tangcloud', [])
.directive('tangCloud', ['$interpolate', '$compile', '$timeout', function ($interpolate, $compile, $timeout) {
var directive = {
restrict: 'E',
scope: {
words: '=',
onClick: '&',
spin: '='
},
template: function (tElement, tAttrs) {
var isClickable = angular.isDefined(tAttrs.onClick);
var clickAttr = isClickable ? 'ng-click="onClick({word : entry.word, id : entry.id})"' : '';
return "<div class='tangcloud'>" +
"<span ng-repeat='entry in words'" + clickAttr + ">{{entry.word}}</span>" +
"</div>";
},
compile: function (elem) {
elem.children().children()
.addClass('tangcloud-item-' + $interpolate.startSymbol() + 'entry.size' + $interpolate.endSymbol())
.addClass('tangcloud-item-hidden');
return function (scope, elem) {
var div = elem.children().eq(0)[0];
scope.width = div.offsetWidth;
scope.height = div.offsetHeight;
var centerX = scope.width / 2;
var centerY = scope.height / 2;
var outOfBoundsCount = 0;
var takenSpots = [];
if (scope.words) {
scope.words = shuffleWords(scope.words);
determineWordPositions();
}
function shuffleWords(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
function determineWordPositions() {
$timeout(function () {
var trendSpans = elem.children().eq(0).children();
var length = trendSpans.length;
for (var i = 0; i < length; i++) {
setWordSpanPosition(trendSpans.eq(i));
}
});
}
function setWordSpanPosition(span) {
var height = parseInt(window.getComputedStyle(span[0]).lineHeight, 10);
var width = span[0].offsetWidth;
var spot = setupDefaultSpot(width, height);
var angleMultiplier = 0;
while (spotNotUsable(spot) && outOfBoundsCount < 50) {
spot = moveSpotOnSpiral(spot, angleMultiplier);
angleMultiplier += 1;
}
if (outOfBoundsCount < 50) {
takenSpots.push(spot);
addSpanPositionStyling(span, spot.startX, spot.startY);
}
outOfBoundsCount = 0;
}
function setupDefaultSpot(width, height) {
return {
width: width,
height: height,
startX: centerX - width / 2,
startY: centerY - height / 2,
endX: centerX + width / 2,
endY: centerY + height / 2
};
}
function moveSpotOnSpiral(spot, angleMultiplier) {
var angle = angleMultiplier * 0.1;
spot.startX = centerX + (1.5 * angle) * Math.cos(angle) - (spot.width / 2);
spot.startY = centerY + angle * Math.sin(angle) - (spot.height / 2);
spot.endX = spot.startX + spot.width;
spot.endY = spot.startY + spot.height;
return spot;
}
function spotNotUsable(spot) {
var borders = {
left: centerX - scope.width / 2,
right: centerX + scope.width / 2,
bottom: centerY - scope.height / 2,
top: centerY + scope.height / 2
};
for (var i = 0; i < takenSpots.length; i++) {
if (spotOutOfBounds(spot, borders) || collisionDetected(spot, takenSpots[i])) return true;
}
return false;
}
function spotOutOfBounds(spot, borders) {
if (spot.startX < borders.left ||
spot.endX > borders.right ||
spot.startY < borders.bottom ||
spot.endY > borders.top) {
outOfBoundsCount++;
return true;
} else {
return false;
}
}
function collisionDetected(spot, takenSpot) {
if (spot.startX > takenSpot.endX || spot.endX < takenSpot.startX) {
return false;
}
return !(spot.startY > takenSpot.endY || spot.endY < takenSpot.startY);
}
function addSpanPositionStyling(span, startX, startY) {
var style = "position: absolute; left:" + startX + "px; top: " + startY + "px;";
span.attr("style", style);
span.removeClass("tangcloud-item-hidden");
}
};
}
};
return directive;
}]);
How can I refresh my directive on change the input for my word-cloud
I am trying to implement angular-slider using angularJS v-1.2.20.
<div ng-controller="ItemCtrl">
<slider custom-floor="item.minAge" floor="100" custom-ceiling="item.maxAge" ceiling="1000" step="10" precision="2" ng-model="item.cost"></slider>
</div>
After including all necessary js and css files, the slider is shown but the floor and ceiling values(and also custom floor and custom ceiling values) are not getting displayed.
There is no error in console. But when I used angular v-1.1.4 in the script without changing any code, everything seems to work fine.
Does anybody know about this issue. Any workaround if I need to use slider with angular v-1.2.20.?
Thanks for Help!
First of all sorry for my english,the ng-bind-html-unsafe was deleted of angular js so we now need to use directly "{{}}" in html code i just change attribute by a call in html and angular slider works with at least angular 1.2.9 that i used, here a complete exemple.
<!DOCTYPE html>
<html ng-app="APP">
<head>
<meta charset="UTF-8">
<title>angular-slider example</title>
<link rel="stylesheet" href="http://www.directiv.es/application/html/js/prajwalkman/angular-slider/angular-slider.min.css" media="all">
</head>
<body>
<div style="width:600px;" ng-controller="ItemCtrl">
<slider floor="0" ceiling="100" step="1" precision="2" ng-model="cost"></slider>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<script>// Generated by CoffeeScript 1.6.2
(function() {
var MODULE_NAME, SLIDER_TAG, angularize, bindHtml, gap, halfWidth, hide, inputEvents, module, offset, offsetLeft, pixelize, qualifiedDirectiveDefinition, roundStep, show, sliderDirective, width;
MODULE_NAME = 'uiSlider';
SLIDER_TAG = 'slider';
angularize = function(element) {
return angular.element(element);
};
pixelize = function(position) {
return "" + position + "px";
};
hide = function(element) {
return element.css({
opacity: 0
});
};
show = function(element) {
return element.css({
opacity: 1
});
};
offset = function(element, position) {
return element.css({
left: position
});
};
halfWidth = function(element) {
return element[0].offsetWidth / 2;
};
offsetLeft = function(element) {
return element[0].offsetLeft;
};
width = function(element) {
return element[0].offsetWidth;
};
gap = function(element1, element2) {
return offsetLeft(element2) - offsetLeft(element1) - width(element1);
};
bindHtml = function(element, html) {
};
roundStep = function(value, precision, step, floor) {
var decimals, remainder, roundedValue, steppedValue;
if (floor == null) {
floor = 0;
}
if (step == null) {
step = 1 / Math.pow(10, precision);
}
remainder = (value - floor) % step;
steppedValue = remainder > (step / 2) ? value + step - remainder : value - remainder;
decimals = Math.pow(10, precision);
roundedValue = steppedValue * decimals / decimals;
return roundedValue.toFixed(precision);
};
inputEvents = {
mouse: {
start: 'mousedown',
move: 'mousemove',
end: 'mouseup'
},
touch: {
start: 'touchstart',
move: 'touchmove',
end: 'touchend'
}
};
sliderDirective = function($timeout) {
return {
restrict: 'EA',
scope: {
floor: '#',
ceiling: '#',
step: '#',
precision: '#',
ngModel: '=?',
ngModelLow: '=?',
ngModelHigh: '=?',
translate: '&'
},
template: '<span class="bar"></span><span class="bar selection"></span><span class="pointer"></span><span class="pointer"></span><span class="bubble selection"></span><span class="bubble limit"> {{floor}}</span><span class="bubble limit">{{ ceiling}}</span><span class="bubble">{{ngModel}}</span><span class="bubble"></span><span class="bubble"></span>',
compile: function(element, attributes) {
var ceilBub, cmbBub, e, flrBub, fullBar, highBub, lowBub, maxPtr, minPtr, range, refHigh, refLow, selBar, selBub, watchables, _i, _len, _ref, _ref1;
if (attributes.translate) {
attributes.$set('translate', "" + attributes.translate + "(value)");
}
range = (attributes.ngModel == null) && ((attributes.ngModelLow != null) && (attributes.ngModelHigh != null));
_ref = (function() {
var _i, _len, _ref, _results;
_ref = element.children();
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
e = _ref[_i];
_results.push(angularize(e));
}
return _results;
})(), fullBar = _ref[0], selBar = _ref[1], minPtr = _ref[2], maxPtr = _ref[3], selBub = _ref[4], flrBub = _ref[5], ceilBub = _ref[6], lowBub = _ref[7], highBub = _ref[8], cmbBub = _ref[9];
refLow = range ? 'ngModelLow' : 'ngModel';
refHigh = 'ngModelHigh';
bindHtml(selBub, "'Range: ' + translate({value: diff})");
bindHtml(lowBub, "translate({value: " + refLow + "})");
bindHtml(highBub, "translate({value: " + refHigh + "})");
bindHtml(cmbBub, "translate({value: " + refLow + "}) + ' - ' + translate({value: " + refHigh + "})");
if (!range) {
_ref1 = [selBar, maxPtr, selBub, highBub, cmbBub];
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
element = _ref1[_i];
element.remove();
}
}
watchables = [refLow, 'floor', 'ceiling'];
if (range) {
watchables.push(refHigh);
}
return {
post: function(scope, element, attributes) {
var barWidth, boundToInputs, dimensions, maxOffset, maxValue, minOffset, minValue, ngDocument, offsetRange, pointerHalfWidth, updateDOM, valueRange, w, _j, _len1;
boundToInputs = false;
ngDocument = angularize(document);
if (!attributes.translate) {
scope.translate = function(value) {
return value.value;
};
}
pointerHalfWidth = barWidth = minOffset = maxOffset = minValue = maxValue = valueRange = offsetRange = void 0;
dimensions = function() {
var value, _j, _len1, _ref2, _ref3;
if ((_ref2 = scope.precision) == null) {
scope.precision = 0;
}
if ((_ref3 = scope.step) == null) {
scope.step = 1;
}
for (_j = 0, _len1 = watchables.length; _j < _len1; _j++) {
value = watchables[_j];
scope[value] = roundStep(parseFloat(scope[value]), parseInt(scope.precision), parseFloat(scope.step), parseFloat(scope.floor));
}
scope.diff = roundStep(scope[refHigh] - scope[refLow], parseInt(scope.precision), parseFloat(scope.step), parseFloat(scope.floor));
pointerHalfWidth = halfWidth(minPtr);
barWidth = width(fullBar);
minOffset = 0;
maxOffset = barWidth - width(minPtr);
minValue = parseFloat(attributes.floor);
maxValue = parseFloat(attributes.ceiling);
valueRange = maxValue - minValue;
return offsetRange = maxOffset - minOffset;
};
updateDOM = function() {
var adjustBubbles, bindToInputEvents, fitToBar, percentOffset, percentToOffset, percentValue, setBindings, setPointers;
dimensions();
percentOffset = function(offset) {
return ((offset - minOffset) / offsetRange) * 100;
};
percentValue = function(value) {
return ((value - minValue) / valueRange) * 100;
};
percentToOffset = function(percent) {
return pixelize(percent * offsetRange / 100);
};
fitToBar = function(element) {
return offset(element, pixelize(Math.min(Math.max(0, offsetLeft(element)), barWidth - width(element))));
};
setPointers = function() {
var newHighValue, newLowValue;
offset(ceilBub, pixelize(barWidth - width(ceilBub)));
newLowValue = percentValue(scope[refLow]);
offset(minPtr, percentToOffset(newLowValue));
offset(lowBub, pixelize(offsetLeft(minPtr) - (halfWidth(lowBub)) + pointerHalfWidth));
if (range) {
newHighValue = percentValue(scope[refHigh]);
offset(maxPtr, percentToOffset(newHighValue));
offset(highBub, pixelize(offsetLeft(maxPtr) - (halfWidth(highBub)) + pointerHalfWidth));
offset(selBar, pixelize(offsetLeft(minPtr) + pointerHalfWidth));
selBar.css({
width: percentToOffset(newHighValue - newLowValue)
});
offset(selBub, pixelize(offsetLeft(selBar) + halfWidth(selBar) - halfWidth(selBub)));
return offset(cmbBub, pixelize(offsetLeft(selBar) + halfWidth(selBar) - halfWidth(cmbBub)));
}
};
adjustBubbles = function() {
var bubToAdjust;
fitToBar(lowBub);
bubToAdjust = highBub;
if (range) {
fitToBar(highBub);
fitToBar(selBub);
if (gap(lowBub, highBub) < 10) {
hide(lowBub);
hide(highBub);
fitToBar(cmbBub);
show(cmbBub);
bubToAdjust = cmbBub;
} else {
show(lowBub);
show(highBub);
hide(cmbBub);
bubToAdjust = highBub;
}
}
if (gap(flrBub, lowBub) < 5) {
hide(flrBub);
} else {
if (range) {
if (gap(flrBub, bubToAdjust) < 5) {
hide(flrBub);
} else {
show(flrBub);
}
} else {
show(flrBub);
}
}
if (gap(lowBub, ceilBub) < 5) {
return hide(ceilBub);
} else {
if (range) {
if (gap(bubToAdjust, ceilBub) < 5) {
return hide(ceilBub);
} else {
return show(ceilBub);
}
} else {
return show(ceilBub);
}
}
};
bindToInputEvents = function(pointer, ref, events) {
var onEnd, onMove, onStart;
onEnd = function() {
pointer.removeClass('active');
ngDocument.unbind(events.move);
return ngDocument.unbind(events.end);
};
onMove = function(event) {
var eventX, newOffset, newPercent, newValue;
eventX = event.clientX || event.touches[0].clientX;
newOffset = eventX - element[0].getBoundingClientRect().left - pointerHalfWidth;
newOffset = Math.max(Math.min(newOffset, maxOffset), minOffset);
newPercent = percentOffset(newOffset);
newValue = minValue + (valueRange * newPercent / 100.0);
if (range) {
if (ref === refLow) {
if (newValue > scope[refHigh]) {
ref = refHigh;
minPtr.removeClass('active');
maxPtr.addClass('active');
}
} else {
if (newValue < scope[refLow]) {
ref = refLow;
maxPtr.removeClass('active');
minPtr.addClass('active');
}
}
}
newValue = roundStep(newValue, parseInt(scope.precision), parseFloat(scope.step), parseFloat(scope.floor));
scope[ref] = newValue;
return scope.$apply();
};
onStart = function(event) {
pointer.addClass('active');
dimensions();
event.stopPropagation();
event.preventDefault();
ngDocument.bind(events.move, onMove);
return ngDocument.bind(events.end, onEnd);
};
return pointer.bind(events.start, onStart);
};
setBindings = function() {
var bind, inputMethod, _j, _len1, _ref2, _results;
boundToInputs = true;
bind = function(method) {
bindToInputEvents(minPtr, refLow, inputEvents[method]);
return bindToInputEvents(maxPtr, refHigh, inputEvents[method]);
};
_ref2 = ['touch', 'mouse'];
_results = [];
for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) {
inputMethod = _ref2[_j];
_results.push(bind(inputMethod));
}
return _results;
};
setPointers();
adjustBubbles();
if (!boundToInputs) {
return setBindings();
}
};
$timeout(updateDOM);
for (_j = 0, _len1 = watchables.length; _j < _len1; _j++) {
w = watchables[_j];
scope.$watch(w, updateDOM);
}
return window.addEventListener("resize", updateDOM);
}
};
}
};
};
qualifiedDirectiveDefinition = ['$timeout', sliderDirective];
module = function(window, angular) {
return angular.module(MODULE_NAME, []).directive(SLIDER_TAG, qualifiedDirectiveDefinition);
};
module(window, window.angular);
}).call(this);</script>
<script>
app = angular.module('APP', ['uiSlider']);
app.controller('ItemCtrl', ['$scope', function($scope) {
$scope.cost = 0
}]);
</script>
</body>
</html>