Why this component doesnt work if I use: polymer init app-drawer-template - polymer-1.0

Hi Im just a rookie with polymer, I hope this question doesnt sound stupid for you :(
I am triying to make a image gallery and I am using this idea: From this page
<dom-module id="simple-gallery" >
<script>
HTMLImports.whenReady(function () {
(function() {
var current_index = 0;
var image_length = 0;
Polymer({
is: "simple-gallery",
ready: function() {
var images = Polymer.dom(this).querySelectorAll('img');
var container = this.$.links;
for (var img in images) {
images[img].addEventListener('click',this.load_popup);
container.appendChild(images[img]);
}
},
load_popup: function(e, detail, sender) {
e.preventDefault();
var links = document.getElementById('links');
image_length = links.getElementsByTagName('img').length;
var image_url = e.target.getAttribute('data-original');
var modalbody = document.getElementsByClassName("modal-body")[0];
var modal_img = modalbody.getElementsByTagName('img')[0];
modal_img.setAttribute("src",image_url);
var modal = document.getElementsByClassName("modal")[0];
modal.style.display = 'block';
current_index = parseInt(e.target.getAttribute('data-index').replace("s",""));
return false;
},
next: function () {
current_index = current_index + 1;
if(current_index == (image_length + 1) ){
current_index = 1;
}
var current_image = document.querySelectorAll("[data-index='s"+current_index+"']");
image_url = current_image[0].getAttribute('data-original');
var modalbody = document.getElementsByClassName("modal-body")[0];
var modal_img = modalbody.getElementsByTagName('img')[0];
modal_img.setAttribute("src",image_url);
},
prev: function () {
current_index = current_index - 1;
if(current_index == 0 ){
current_index = image_length;
}
var current_image = document.querySelectorAll("[data-index='s"+current_index+"']");
image_url = current_image[0].getAttribute('data-original');
var modalbody = document.getElementsByClassName("modal-body")[0];
var modal_img = modalbody.getElementsByTagName('img')[0];
modal_img.setAttribute("src",image_url);
},
close: function () {
var modal = document.getElementsByClassName("modal")[0];
modal.style.display = "none";
},
});
})();
});
</script>
<template>
I realy dont understand why this code works fine if I use it as in the example, but if I create a proyect with: polymer init app-drawer-template and I use this as an element wich is called from one of the views I have an error :(
Uncaught ReferenceError: HTMLImports is not defined(anonymous function) # simple-gallery.html:91
Surely I am not understanding well something but I dont know why, hope somebody has the time to give me a brief explanation :(
thanks a lot for your time.

I had the same issue so I have added following include in my main html:
<script src="bower_components/webcomponentsjs/webcomponents-lite.js"></script>
Which worked for me.

Related

getting the inner html of a contenteditable div in angularjs

I am trying to get innerHTML of a contenteditable div via function defined in controller of angularjs but it returns undefined every time.. what are the alternatives or how can I handle this issue?
$scope.genrate_HTML=function()
{
var read_string=document.getElementsByClassName("MainPage");
//console.log(read_string);
var p_tag= '\n<p id="test"> \n'+read_string.innerHTML+'\n </p>';
//document.getElementById("createdHTML").value = p_tag ;
//$compile( document.getElementById('createdHTML') )($scope);
}
the contenteditble div's classs name is "MainPage"
VisualEditor.controller("GenrateHTML",function($scope){
$scope.savefile=function()
{
$scope.genratedHTML_text=document.getElementById("createdHTML").value;
var text_file_blob= new Blob([$scope.genratedHTML_text],{type:'text/html'});
$scope.file_name_to_save=document.getElementById("file_name").value ;
var downloadLink=document.createElement("a");
downloadLink.download=$scope.file_name_to_save;
downloadLink.innerHTML="Download File";
if(window.URL!=null)
{
downloadLink.href=window.URL.createObjectURL(text_file_blob);
}
else
{
downloadLink.href = window.URL.createObjectURL(text_file_blob);
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
}
function destroyClickedElement(event)
{
document.body.removeChild(event.target);
}
$scope.toggleModal = function(){
$scope.showModal = !$scope.showModal;
};
///add details
$scope.details=[];
$scope.addDetails=function(){
$scope.details.push({
Title:$scope.Details_Title,
meta_chars:$scope.Details_metaChars,
version:$scope.Details_version,
Auth_name:$scope.Details_AuthName,
copyRights:$scope.Details_copyRights
});
document.getElementById("createdHTML").innerHTML = $scope.details;
};
$scope.$watch('details', function (value) {
console.log(value);
}, true);
/////////////////////
$scope.genrate_HTML=function()
{
var read_string=document.getElementsByClassName("MainPage");
//console.log(read_string);
var p_tag = '';
for (var i = 0; i < read_string.length; i++) {
p_tag += '\n<p id="test_"' + i + '> \n' + read_string[i].innerHTML + '\n </p>';
document.getElementById("createdHTML").value = p_tag;
}
//$compile( document.getElementById('createdHTML') )($scope);
}
});
getElementsByClassName returns an Array, so, your read_string variable is an Array type. you should iterate through the elements of read_string with for loop.
NOTE: Please check the p element's id here aswell. Because id must be unique!
$scope.genrate_HTML = function() {
var read_string = document.getElementsByClassName("MainPage");
var p_tag = '';
for (var i = 0; i < read_string.length; i++) {
p_tag += '\n<p id="test_"'+i+'> \n'+read_string[i].innerHTML+'\n </p>';
}
/* Other code here... */
}
UPDATE: Don't use the code below! If read_string returns with no elements than your code will crash!
But if it's a 1 element Array then you can take the value like:
$scope.genrate_HTML = function() {
var read_string = document.getElementsByClassName("MainPage");
var p_tag= '\n<p id="test"> \n'+read_string[0].innerHTML+'\n </p>';
/* Other code here... */
}
I hope that helps. If it doesn't then paste the full code of the Controller.

$compile within $compile not getting applied

I have a directive which takes in an array of container objects and $compiles a new container directive for each container and each nested container. It also compiles a resize handle before all containers except the first child. The link function looks like this:
//scope.dock is retrieved from a factory
scope.initContainers = function () {
var prevScope;
for (var i = 0; i < scope.dock.containers.length; i++) {
var newScope = scope.$new(true);
newScope.container = scope.dock.containers[i];
var newElement = '<panel-container class=\"' + scope.dock.containers[i].axis + '" ></panel-container>';
var newTemplate = $compile(newElement)(newScope);
if (i > 0) {
var sizerScope = scope.$new(true);
sizerScope.containerOne = prevScope;
sizerScope.containerTwo = newScope;
var sizerElement = '<resize-handle class=\"' + scope.dock.containers[i].axis + '"></resize-handle>';
var sizerTemplate = $compile(sizerElement)(sizerScope);
element.append(sizerTemplate);
}
element.append(newTemplate);
if (scope.dock.containers[i].containers.length > 0) {
generateContainers(scope.dock.containers[i], newScope, newTemplate);
}
}
return scope;
};
scope.sizeContainers = function () {
scope.$broadcast('size-containers');
};
var generateContainers = function (value, parentScope, parentElement) {
var prevScope;
for (var y = 0; y < value.containers.length; y++) {
var newChildScope = parentScope.$new(true);
newChildScope.container = value.containers[y];
var newChildElement = '<panel-container class=\"' + value.containers[y].axis + '" ></panel-container>';
var newChildTemplate = $compile(newChildElement)(newChildScope);
if (y > 0) {
var sizerScope = parentScope.$new(true);
sizerScope.containerOne = prevScope;
sizerScope.containerTwo = newChildScope;
var sizerElement = '<resize-handle class=\"' + value.containers[y].axis + '"></resize-handle>';
var sizerTemplate = $compile(sizerElement)(sizerScope);
parentElement.append(sizerTemplate);
}
parentElement.append(newChildTemplate);
if(typeof value.containers[y].containers !== 'undefined') {
if (value.containers[y].containers.length > 0) {
generateContainers(value.containers[y], newChildScope, newChildTemplate);
}
}
prevScope = newChildScope;
}
};
scope.initContainers().sizeContainers();
My problem is that the first child layer compiles but the second one does not. It does, however, work when I add scope.$apply to the end of generateContainers. Unfortunately for some reason it is skipping the first child element for each container and throwing a 'digest in progress' error.
Does anyone have any ideas on how to get this to compile?
And could someone explain why scope.$apply() is compiling the second layer only after I explicitly call it, even when $digest is already running?
I fixed this by getting rid of initContainers (since it was exactly the same as generateContainers) and moving that function to the container directive as well. That way the root directive wasn't trying to compile everything.

server handlers in Google app script sheets not working

I get this error when trying to execute this code from the script manager menu.
Error encountered: Script function not found: function click(e) {
var app = UiApp.getActiveApplication();
app.getElementById('label').setVisible(false);
SpreadsheetApp.getActiveSpreadsheet().show(ui);
return app;
}
function readRows() {
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
for (var i = 0; i <= numRows - 1; i++) {
var row = values[i];
Logger.log(row);
}
};
function onOpen() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var entries = [{
name : "ShowUi",
functionName : "showSidebar"
}];
spreadsheet.addMenu("Script Center Menu", entries);
};
function click(e) {
var app = UiApp.getActiveApplication();
app.getElementById('label').setVisible(false);
SpreadsheetApp.getActiveSpreadsheet().show(ui);
return app;
}
function showSidebar(e){
var ui= UiApp.createApplication()
.setTitle('My UiApp Application')
.setWidth(250)
.setHeight(300);
var button = ui.createButton("I am a button!");
var handler = ui.createServerHandler(click);
button.addClickHandler(handler);
var label =ui.createLabel('The photograph on the dashboard taken years ago...').setId('label').setVisible(false);
handler.addCallbackElement(label).addCallbackElement(button);
ui.add(label);
ui.add(button);
SpreadsheetApp.getActiveSpreadsheet().show(ui);
return ui;
};
I'm sorry that I had to post here for probably obvious but I could not find the answer anywhere else on the internet. Any solution or alternate way i could do the same thing would be greatly appreciated. thanks!
Try something like this:
function showSidebar(e){
var ui= UiApp.createApplication()
.setTitle('My UiApp Application')
.setWidth(250)
.setHeight(300);
var label = ui.createLabel('The photograph on the dashboard taken years ago...').setId('label').setVisible(false);
ui.add(label);
ui.add(ui.createButton('I am a button!', ui.createServerHandler('onClick')).setId('button'));
SpreadsheetApp.getActiveSpreadsheet().show(ui);
return ui;
};
function onClick(e) {
var app = UiApp.getActiveApplication();
app.getElementById('label').setVisible(false);
//SpreadsheetApp.getActiveSpreadsheet().show(ui);
app.close();
return app;
};

accessing items in firebase

I'm trying to learn firebase/angularjs by extending an app to use firebase as the backend.
My forge looks like this
.
In my program I have binded firebaseio.com/projects to $scope.projects.
How do I access the children?
Why doesn't $scope.projects.getIndex() return the keys to the children?
I know the items are in $scope.projects because I can see them if I do console.log($scope.projects)
app.js
angular.module('todo', ['ionic', 'firebase'])
/**
* The Projects factory handles saving and loading projects
* from localStorage, and also lets us save and load the
* last active project index.
*/
.factory('Projects', function() {
return {
all: function () {
var projectString = window.localStorage['projects'];
if(projectString) {
return angular.fromJson(projectString);
}
return [];
},
// just saves all the projects everytime
save: function(projects) {
window.localStorage['projects'] = angular.toJson(projects);
},
newProject: function(projectTitle) {
// Add a new project
return {
title: projectTitle,
tasks: []
};
},
getLastActiveIndex: function () {
return parseInt(window.localStorage['lastActiveProject']) || 0;
},
setLastActiveIndex: function (index) {
window.localStorage['lastActiveProject'] = index;
}
}
})
.controller('TodoCtrl', function($scope, $timeout, $ionicModal, Projects, $firebase) {
// Load or initialize projects
//$scope.projects = Projects.all();
var projectsUrl = "https://ionic-guide-harry.firebaseio.com/projects";
var projectRef = new Firebase(projectsUrl);
$scope.projects = $firebase(projectRef);
$scope.projects.$on("loaded", function() {
var keys = $scope.projects.$getIndex();
console.log($scope.projects.$child('-JGTmBu4aeToOSGmgCo1'));
// Grab the last active, or the first project
$scope.activeProject = $scope.projects.$child("" + keys[0]);
});
// A utility function for creating a new project
// with the given projectTitle
var createProject = function(projectTitle) {
var newProject = Projects.newProject(projectTitle);
$scope.projects.$add(newProject);
Projects.save($scope.projects);
$scope.selectProject(newProject, $scope.projects.length-1);
};
// Called to create a new project
$scope.newProject = function() {
var projectTitle = prompt('Project name');
if(projectTitle) {
createProject(projectTitle);
}
};
// Called to select the given project
$scope.selectProject = function(project, index) {
$scope.activeProject = project;
Projects.setLastActiveIndex(index);
$scope.sideMenuController.close();
};
// Create our modal
$ionicModal.fromTemplateUrl('new-task.html', function(modal) {
$scope.taskModal = modal;
}, {
scope: $scope
});
$scope.createTask = function(task) {
if(!$scope.activeProject || !task) {
return;
}
console.log($scope.activeProject.task);
$scope.activeProject.task.$add({
title: task.title
});
$scope.taskModal.hide();
// Inefficient, but save all the projects
Projects.save($scope.projects);
task.title = "";
};
$scope.newTask = function() {
$scope.taskModal.show();
};
$scope.closeNewTask = function() {
$scope.taskModal.hide();
};
$scope.toggleProjects = function() {
$scope.sideMenuController.toggleLeft();
};
// Try to create the first project, make sure to defer
// this by using $timeout so everything is initialized
// properly
$timeout(function() {
if($scope.projects.length == 0) {
while(true) {
var projectTitle = prompt('Your first project title:');
if(projectTitle) {
createProject(projectTitle);
break;
}
}
}
});
});
I'm interested in the objects at the bottom
console.log($scope.projects)
Update
After digging around it seems I may be accessing the data incorrectly. https://www.firebase.com/docs/reading-data.html
Here's my new approach
// Load or initialize projects
//$scope.projects = Projects.all();
var projectsUrl = "https://ionic-guide-harry.firebaseio.com/projects";
var projectRef = new Firebase(projectsUrl);
projectRef.on('value', function(snapshot) {
if(snapshot.val() === null) {
console.log('location does not exist');
} else {
console.log(snapshot.val()['-JGTdgGAfq7dqBpSk2ls']);
}
});
$scope.projects = $firebase(projectRef);
$scope.projects.$on("loaded", function() {
// Grab the last active, or the first project
$scope.activeProject = $scope.projects.$child("a");
});
I'm still not sure how to traverse the keys programmatically but I feel I'm getting close
It's an object containing more objects, loop it with for in:
for (var key in $scope.projects) {
if ($scope.projects.hasOwnProperty(key)) {
console.log("The key is: " + key);
console.log("The value is: " + $scope.projects[key]);
}
}
ok so val() returns an object. In order to traverse all the children of projects I do
// Load or initialize projects
//$scope.projects = Projects.all();
var projectsUrl = "https://ionic-guide-harry.firebaseio.com/projects";
var projectRef = new Firebase(projectsUrl);
projectRef.on('value', function(snapshot) {
if(snapshot.val() === null) {
console.log('location does not exist');
} else {
var keys = Object.keys(snapshot.val());
console.log(snapshot.val()[keys[0]]);
}
});
$scope.projects = $firebase(projectRef);
$scope.projects.$on("loaded", function() {
// Grab the last active, or the first project
$scope.activeProject = $scope.projects.$child("a");
});
Note the var keys = Object.keys() gets all the keys at firebaseio.com/projects then you can get the first child by doing snapshot.val()[keys[0])

How to Nested use “Require.js” with "backbone.js"?

I'm doing the application, the use of backbone.js and require.js, I would like to achieve dynamic configuration module navigation by the "backbone.router" function, here is my question?
This is my baserouter defined,I want to achieve dynamic load "backbone.view" according to "the viewPath" parameter.How can I do?
define(['require', 'underscore', 'backbone'], function(require, _, Backbone) {
var BaseRouter = Backbone.Router.extend({
container: "#page",
loadView: function(viewPath) {
**//Here require lazy loading "base/people/view.js", **
**//I do not know how to achieve it?**
var view = require(viewPath);//viewPath = "base/people/view";
this._currentView = new view();
this._currentView.render();
$(this.container).html(this._currentView.el);
}
});
return BaseRouter;
});
This is the definition of the router, it work with "baserouter" to dynamically set the navigation menu.
define(['baserouter'], function(baserouter) {
//The JSON data should come from the database,
//These data define the navigation information for all modules.
var navs = JSON.parse('[{"name": "people","title": "peoplemanage","view": "base/people/view"},{"name": "test","title": "testmanage","view": "pub/test/view"}]');
var AppRouter = baserouter.extend();
for (var i = 0, l = navs.length; i < l; i++) {
var nav = navs[i];
AppRouter.prototype["loadView_" + nav.name] = function() {
var path = nav.view;
return function() {
AppRouter.prototype.loadView(path);
}
}();
}
var initialize = function() {
var routes = {}
for (var i = 0, l = navs.length; i < l; i++) {
var nav = navs[i];
routes[nav.name] = "loadView_" + nav.name;
}
var app_router = new AppRouter({
"routes": routes
});
Backbone.history.start();
};
return {
initialize: initialize
};
});
Here is the html code for the navigation menu:
<ul class="dropdown-menu">
<li>people</li>
<li>test</li>
</ul>
This method can achieve.But I'm not sure this is the best practice, and who has a better way?
loadView: function(viewPath) {
var _this = this;
if (this._currentView) {
this._currentView.dispose();
}
//var view = require(viewPath);
//**This method can achieve.But I'm not sure this is the best practice, and who has a better way?**
//setTimeout(function() {
require([viewPath], function(view) {
_this._currentView = new view();
_this._currentView.render();
$("#page").html(_this._currentView.el);
});
//}, 100);

Resources