Combine HTML and JS from Fiddle - javascript

A similar question was asked in this forum post, but I am still unable to convert the code from JSfiddle to HTML.
The JSfiddle example can be found here.
I tried to use the technique suggested in the forum post previously mentioned, that is:
<html>
<head>
<style type="text/css">
// CSS Content
</style>
</head>
<body ng-app="myApp">
<!-- some html elements -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script language="JavaScript" type="text/javascript">
// more js here.
</script>
</body>
As I am a complete noob, I simply copied the HTML and Javascript into the some html elements and // more js here sections. Without changing the API key, the final code looked like this:
<html>
<head>
<style type="text/css">
// CSS Content
</style>
</head>
<body ng-app="myApp">
<div ng-app="myapp" ng-controller="WeatherCtrl">
<h2>Weather in Salzburg, Austria</h2>
<weather-icon cloudiness="{{ weather.clouds }}"></weather-icon>
<h3>Current: {{ weather.temp.current | temp:2 }}</h3>
min: {{ weather.temp.min | temp }}, max: {{ weather.temp.max | temp }}
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script language="JavaScript" type="text/javascript">
'use strict';
var myapp = angular.module('myapp', []);
myapp.factory('weatherService', function($http) {
return {
getWeather: function() {
var weather = { temp: {}, clouds: null };
$http.jsonp('http://api.openweathermap.org/data/2.5/weather?q=Salzburg,at&units=metric&callback=JSON_CALLBACK&APPID=f9dbd911bc01df1d9ce563b2ba4d3209').success(function(data) {
if (data) {
if (data.main) {
weather.temp.current = data.main.temp;
weather.temp.min = data.main.temp_min;
weather.temp.max = data.main.temp_max;
}
weather.clouds = data.clouds ? data.clouds.all : undefined;
}
});
return weather;
}
};
});
myapp.filter('temp', function($filter) {
return function(input, precision) {
if (!precision) {
precision = 1;
}
var numberFilter = $filter('number');
return numberFilter(input, precision) + '\u00B0C';
};
});
myapp.controller('WeatherCtrl', function ($scope, weatherService) {
$scope.weather = weatherService.getWeather();
});
myapp.directive('weatherIcon', function() {
return {
restrict: 'E', replace: true,
scope: {
cloudiness: '#'
},
controller: function($scope) {
$scope.imgurl = function() {
var baseUrl = 'https://ssl.gstatic.com/onebox/weather/128/';
if ($scope.cloudiness < 20) {
return baseUrl + 'sunny.png';
} else if ($scope.cloudiness < 90) {
return baseUrl + 'partly_cloudy.png';
} else {
return baseUrl + 'cloudy.png';
}
};
},
template: '<div style="float:left"><img ng-src="{{ imgurl() }}"></div>'
};
});
</script>
</body>
My output looks like this:
Could anyone please show me how to do this?

The problem is that you are declaring two apps remove "ng-app="myApp" from the body <body> tag.

Related

value $scope is undefined

I have 2 files. First one :
<script>
var demo=angular.module('demo', []);
demo.controller('scoresCtrl', function($scope, $http) {
$http.get('http://localhost/scores').then(function(response) {
$scope.scores = response.data;
});
});
</script>
Another file index.html
<head><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<script src="scoresCtrl.js"></script>
<script>
function run(){
var data=angular.element(document.getElementById("scoresBodyId")).scope().scores;
alert(data);
}
</script></head>
<body onload="run()" id="scoresBodyId" ng-controller="scoresCtrl" >
</body>
When I tried to display alert(data) , I got undefined
but when I replace onload by onclick , after Clicking I obtained my value. I would like to use onload. Thanks for your explanation and your help.
You need to change onload to ng-init to call your function on body
Controller
var demo = angular.module('demo', []);
demo.controller('scoresCtrl', function($scope, $http) {
$scope.run = function() {
$http.get('http://localhost/scores').then(function(response) {
$scope.scores = response.data;
alert($scope.scores);
});
}
});
index.html
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<script src="scoresCtrl.js"></script>
</head>
<body ng-init="run()" id="scoresBodyId" ng-controller="scoresCtrl">
</body>

How to send value in JavaScript variable to a Angular js variable

I am having a problem sending a value of JavaScript variable to Angular js variable. I want to send a value in dataArray variable in JavaScript to Angular js variable $scope.test
html code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="angular.js"></script>
<script type='text/javascript'>
$(document).ready(function () {
// $("#fileUpload").load('test.csv');
$.get("test.csv", function(data) {
alert(data);
var rows = data.split("\r\n");
if(rows.length>0){
alert("inside if");
var firstRowCells = GetCSVCells(rows[0], ",");
var dataArray = new Array();
for(var i=1;i<rows.length;i++)
{
var cells = GetCSVCells(rows[i], ",");
var obj = {};
for(var j=0;j<cells.length;j++)
{
obj[firstRowCells[j]] = cells[j];
}
dataArray.push(obj);
}
$("#dvCSV").html('');
alert(dataArray);
$("#dvCSV").append(JSON.stringify(dataArray));
var myjson=JSON.stringify(dataArray);
//alert(myjson);
}
});
function GetCSVCells(row, separator){
return row.split(separator);
}
});
</script>
</head>
<body>
<div id="container">
Test
</div>
<div ng-app="sortApp" ng-controller="mainController">
<div id="dvCSV" ng-model="dataf" ng-bind="bdc">dfsgdfd</div>
</div>
<script src="app.js"></script>
</body>
</html>
app.js:
angular.module('sortApp', [])
.controller('mainController', function($scope) {
window.alert("Angular");
window.alert("asdfad"+$scope.bdc);
$scope.test=$scope.dataf;
window.alert($scope.myjson);
window.alert("test"+$scope.test.value);
You can do this all jquery stuff in angular using http service of angular js.
For simple http service you can refer this link -
http://www.w3schools.com/angular/angular_http.asp
I agree with previous answer. Also its wrong to use $(document).ready along with using angular framework in you application.
Try something like this:
angular.module('sortApp', [])
.service('loadTestCsv' ['$http', function($http) {
return $http.get('test.csv').then(data => {
// do all data processing you need
return data;
});
}]);
.controller('mainController', ['$scope', 'loadTestCsv', function($scope, loadTestCsv) {
loadTestCsv().then(data => {
$scope.data = data;
});
}]);

How do I load an html file into ngQuill (Quill Editor)?

I'm using ngQuill, a version of Quill for AngularJS, and I need to know if there is a way to put/load an HTML already created into the editor.
I can't find anything about it in the documentation.
Like always, sorry for my poor english :c
$scope.message = 'Welcome to the Editor!';
$scope.showToolbar = true;
$scope.translations = angular.extend({}, ngQuillConfig.translations, {
10: 'smallest'
});
$scope.toggle = function() {
$scope.showToolbar = !$scope.showToolbar;
};
// Own callback after Editor-Creation
$scope.editorCallback = function (editor, name) {
console.log('createCallback', editor, name);
};
$scope.readOnly = false;
$scope.isReadonly = function () {
return $scope.readOnly;
};
$scope.clear = function () {
return $scope.message = '';
};
// Event after an editor is created --> gets the editor instance on optional the editor name if set
$scope.$on('editorCreated', function (event, editor, name) {
console.log('createEvent', editor, name);
});
$timeout(function () {
$scope.message = 'Async Test Content';
console.log($scope.message);
}, 3000);
<ng-quill-editor
id="editor1"
name="editor1"
callback="editorCallback(editor, name)"
ng-model="message"
translations="translations"
toolbar="true"
show-toolbar="showToolbar"
link-tooltip="true"
image-tooltip="true"
toolbar-entries="font size bold list bullet italic underline strike align color background link image"
editor-required="true"
required=""
read-only="isReadonly()"
error-class="input-error"
fontsize-options="fontsizeOptions"
fontfamily-options="fontfamilyOptions">
</ng-quill-editor>
may be this plnkr could help:
i only included ngSanitize in my main module and it seems to work...
var myAppModule = angular.module('plunker', ['ngQuill','ngSanitize']);
myAppModule.config(['ngQuillConfigProvider', function (ngQuillConfigProvider) {
ngQuillConfigProvider.set();
}]);
myAppModule.controller('AppCtrl', [
'$scope',
'$timeout',
function($scope, $timeout) {
$scope.name='moshe'
$scope.title = '<h1>Quill works</h1>';
$scope.readOnly = false;
$timeout(function () {
$scope.title += ' awsome!!!'
}, 2000);
$scope.editorCreated = function (editor) {
console.log(editor);
};
$scope.contentChanged = function (editor, html, text) {
console.log('editor: ', editor, 'html: ', html, 'text:', text);
};
}
]);
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" href="//cdn.quilljs.com/1.1.5/quill.snow.css">
<link rel="stylesheet" href="//cdn.quilljs.com/1.1.5/quill.bubble.css">
<script data-require="angular.js#1.5.x" src="https://code.angularjs.org/1.5.8/angular.js" data-semver="1.5.8"></script>
<script data-require="angular-sanitize.js#1.5.x" src="https://code.angularjs.org/1.5.8/angular-sanitize.js" data-semver="1.5.8"></script>
<script type="text/javascript" src="//cdn.quilljs.com/1.1.5/quill.js"></script>
<script type="text/javascript" src="http://killercodemonkey.github.io/ng-quill/src/ng-quill.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="AppCtrl">
<p>generated: <i ng-bind-html="title"></i>!</p>
<ng-quill-editor ng-model="title" read-only="readOnly" required="true" modules="{toolbar: true}"></ng-quill-editor>
</body>
</html>
I can't help with Angular, but this was my jQuery solution (for a readOnly page)
Create the editor
Locate your target (where you want the text to be displayed)
Parse your string content
setContents of your editor
var quill = new Quill('#editor-container', { modules: { toolbar: [] }, readOnly: true, theme: 'bubble'} );
var $target = $('#editor-container');
console.log(quill);
console.log(quill.innerText);
var $content = JSON.parse($target[0].innerText);
quill.setContents($content);

Unable to compile a dynamically added Directive into a page

I am trying to add a dynamically added element directive into a page but it is not working and getting compiled in the page it is added. Here is the plunker code. What is wrong with the code?
http://plnkr.co/edit/BFPxAvEahT1I930mvB5r
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller("fCtrl",function($scope,$compile){
$scope.xx = ['x','c','y','z','a'];
$scope.add = function(){
var templ = document.getElementById('test').innerHTML;
templ = templ+'<datan-type content="test1" con="{{xx}}"></datan-type>';
document.getElementById('test').innerHTML = templ;
//$compile(document.getElementById('test').innerHTML)($scope);
alert(document.getElementById('test').innerHTML);
}
});
app.directive('datanType', function ($compile) {
return {
restrict: 'E',
replace: true,
link: function (scope, ele, attrs) {
var testTemplate1 = '<h1 ng-repeat="x in arr">Test{{x}}</h1>';
var testTemplate2 = '<h1>Test2</h1>';
var testTemplate3 = '<h1>Test3</h1>';
var template = '';
scope.arr = eval(attrs.con);
switch(attrs.content){
case 'test1':
template = testTemplate1;
break;
case 'test2':
template = testTemplate2;
break;
case 'test3':
template = testTemplate3;
break;
}
ele.html(template);
$compile(ele.contents())(scope);
}
};
});
</script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body ng-controller="fCtrl">
<p>Result:</p>
<datan-type content="test1" con="{{xx}}"></datan-type>
<div id="test"></div>
<button ng-click="add()">Add Form Elem Eg - Error Area</button>
</body>
</html>
Gary, this was killing me so I made it my morning goal to figure out the silly syntax:
Working Plnkr - Clicky
Change your controller code to :
var elementToAdd = angular.element('<datan-type content="test1" con="{{xx}}"></datan-type>');
$compile(elementToAdd)($scope);
document.getElementById('test').appendChild(elementToAdd[0]);

Ng-Tag-Input Directive not clearing value

I am using ngTagInput directive for auto-suggestion. What I want is clear the auto-suggestion after suggestion is clicked. Though its clearing on first call of function but not on second. It is adding as tag on second function call. and I want to remove that.
On Html,
<tags-input ng-model="autoSongs"
key-property="_id"
display-property="name"
add-from-autocomplete-only="true"
replace-spaces-with-dashes="false"
on-tag-adding="songAdded($tag)"
on-tag-added="emptyScope()"
template="tag-template"
placeholder="type here to search for album..."
on-tag-removed="songRemoved($tag)">
<auto-complete source="loadSongs($query)"
min-length="2"
debounce-delay="5"
max-results-to-show="10"
template="autocomplete-template"></auto-complete>
</tags-input>
This way on controller,
$scope.loadSongs = function(query) {
var autoFilter = 'name=' + query;
return songService.autoSuggest(autoFilter, function(error, data) {
if (error) {
toastr.error(error.message, 'Error');
return false;
}
return data;
});
};
$scope.songAdded = function(query) {
if ($scope.pushArray.checkbox.length === 0) {
toastr.error('Select record to assign album.', 'Error');
return false;
}
var songId = query._id,
songName = query.name;
videoService.assignSong(songId, $scope.pushArray.checkbox, function(err, resonse) {
if (err) {
toastr.error(err.message, 'Error');
} else {
$scope.emptyScope();
toastr.success('\'' + songName + '\' has been assigned to ' + resonse + ' records', 'Success');
$scope.pageChanged();
}
});
return true;
};
$scope.emptyScope = function() {
$scope.autoSongs = null;
};
Its not clearing value on second attempt. Can I use auto-suggestion with callbacks separately?
plunker
If you console log the value of $scope.autoSongs you will find out that it is indeed an array.
So your function that empties the value has to be like this:
$scope.emptyScope = function() {
//$scope.autoSongs = null;
$scope.autoSongs = [];
};
working plunker
PS: please read also this SO answer about emptying an array.
This Plunker seems to work nicely.
on-tag-adding="songAdded($tag)"
Seems to be the only event you need to trigger.
I've tried using $timeout in order to differ emptyScope() function; check if the result is as you want:
var app = angular.module('myApp', ['ngTagsInput']);
app.controller('MainCtrl', function($scope, $timeout, songService) {
$scope.autoSongs = [];
$scope.loadSongs = function(query) {
console.log("loadSongs: " + query);
return songService.autoSuggest(query);
};
$scope.songAdded = function(query) {
console.log("songAdded: " + query);
var songId = query._id,
songName = query.name;
$timeout(function() {
console.log("$timeout: ");
$scope.emptyScope();
});
return true;
};
$scope.emptyScope = function() {
console.log("emptyScope: ");
$scope.autoSongs = [];
};
});
app.factory('songService', function() {
var autoSuggest = function(autoFilter) {
console.log("autoSuggest: " + autoFilter);
if (autoFilter == "i")
return [{name: 'India',_id: 1}, {name: 'Indonesia',_id: 2},{name: 'Italy',_id: 3} ];
else if (autoFilter == "u")
return [{name: 'United Arab',_id: 4}, {name: 'Uganda',_id: 5},{name: 'USA',_id: 6} ];
else
return [{name: 'Germany',_id: 7}, {name: 'Greece',_id: 8},{name: 'Chezk',_id: 9} ];
}
return {autoSuggest:autoSuggest};
});
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<!--link rel="stylesheet" href="style.css" /-->
<link rel="stylesheet" href="http://mbenford.github.io/ngTagsInput/css/ng-tags-input.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
<script src="http://mbenford.github.io/ngTagsInput/js/ng-tags-input.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<tags-input ng-model="autoSongs" key-property="_id" display-property="name" add-from-autocomplete-only="true" replace-spaces-with-dashes="false" on-tag-adding="songAdded($tag)" on-tag-added="emptyScope()" placeholder="type here to search for album..."
on-tag-removed="songRemoved($tag)">
<auto-complete source="loadSongs($query)" min-length="1" debounce-delay="5" max-results-to-show="10"></auto-complete>
</tags-input>
<p>Model: {{autoSongs}}</p>
<p>Search with I or U or else</p>
</body>
</html>
And also the Plunker updated: http://plnkr.co/edit/7nt3toEclsP5HXL7RadP?p=preview

Categories