adding div using javascript that uses angularjs to show data - javascript

I would like to add a div to my current website.
The div i would like to add should show some json data using angularjs.
My problem is that it does not look like angularjs is working like its supose to when adding html after the page is rendered.
Here is my test:
<html >
<head>
<meta charset="utf-8">
<title>Angular test</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>
<script>
var featureInfoMainDivId = 'FeatureInfoMaster';
function initAngularDataFeatureInfo() {
var s = document.createElement('script');
s.type = "text/javascript";
s.textContent =
'var app = angular.module("featureInfoApp", []); ' +
'app.controller("featureInfoCtrl", function ($scope) { ' +
'$scope.firstName = "John" '+
'$scope.lastName = "Doe" ' +
'});';
document.getElementById(featureInfoMainDivId).appendChild(s);
}
function addFeatureInfoDiv() {
var divMain = document.createElement('div');
divMain.setAttribute('id', featureInfoMainDivId);
divMain.setAttribute('ng-app', "featureInfoApp");
divMain.setAttribute('ng-controller', "featureInfoCtrl");
divMain.innerHTML ='<div> {{ firstName + " " + lastName }}</div>';
document.getElementById('appdiv').appendChild(divMain);
initAngularDataFeatureInfo();
}
</script>
<body >
<div id="appdiv"></div>
<button id="btn_load_grid" onclick="addFeatureInfoDiv();">loaddata</button>
</body>
</html>

You are missing two semicolons in
$scope.firstName = "John";
$scope.lastName = "Doe";
If you load the Angular script it looks for ng-app and bootstraps itself. Since you add Angular specific code after the script is loaded, you need to bootstrap Angular manually with:
//after initAngularDataFeatureInfo();
angular.element(document).ready(function() {
angular.bootstrap(document, ['featureInfoApp']);
});
Please remove this line:
divMain.setAttribute('ng-app', "featureInfoApp");
It is not needed if you bootstrap Angular manually. For further bootstrapping info, see: Angular bootstrapping documentation.
Also: Is there a reason why you are using Angular version 1.2.26? Version 1.5.3 is the latest stable build.

Try using Angular directives. you can create a customer directive which will then feed a template of your liking

Related

Application's html loads, but js function built with angular gets stuck loading indefinitely

I'm working on an AngularJS application that reads and writes cookies and my javascript code is not working properly. My html loads fine, but when it comes to load the angular script it gets stuck loading indefinitely.
I've tried with a simple 'hello world' console log with a simple angular function and it works fine, which means the problem is not located on the angular script, but on the cookie function itself, although I can't point out where and since the page's not loading at all, I can't see any output on the console.
Here's my html code.
<!doctype html>
<html ng-app = 'cookieApp'>
<head>
<meta charset="utf-8">
</head>
<body>
<div ng-controller = 'MainController'>
<label>Save cookie:</label>
<input ng-model = 'value'>
<button ng-click = 'saveCookie(value);'>Save</button>
<h2>Get Cookie : {{getCookie()}}</h2>
<script src = 'https://ajax.googleapis.com/ajax/libs/angularjs/1.2.32/angular.js'></script>
<script src = 'app.js'></script>
</div>
</body>
</html>
Here's the javascript code
angular.module('cookieApp', []).controller('MainController', ['$scope', 'cookie', function($scope, cookie){
$scope.value = '';
$scope.saveCookie = function(value){
cookie.write('cap_value', value);
}
$scope.getCookie = function(){
return cookie.read('cap_value');
}
}]).
factory('cookie', [function(){
return{
read: function(name){
var i, c, nameEQ = name + '=';
var ca = document.cookie.split(';');
for(i = 0; i < ca.length; i++){
c = ca[i];
while(c.charAt(0) == ''){
c = c.substring(1, c.length);
}
if(c.indexOf(nameEQ) == 0){
return c.substring(nameEQ.length, c.length);
}
}
return '';
},
write: function(name, value){
date = new Date();
date.setTime(date.getTime() + (72*4));
expires = '; expires = ' + date.toGMTString();
document.cookie = name + '=' + value + expires + '; path = /';
}
}
}]);
I expect the application to save a cookie when I type an input and then print it in the <h2> tag.
Not sure if you're aware of the ngCookies module, but it's basically the answer to your problem. It provides the $cookies service, which is the "proper" way to work with cookies, within an AngularJS application. I've combined your HTML and JavaScript into this snippet, which works exactly as I think you're expecting:
<!doctype html>
<html lang="en" ng-app='cookieApp'>
<head>
<meta charset="UTF-8">
<title>AngularJS Cookie Example</title>
</head>
<body>
<div ng-controller='MainController'>
<label>Save cookie:</label>
<input ng-model='value'>
<button ng-click='saveCookie(value);'>Save</button>
<h2>Get Cookie : {{getCookie()}}</h2>
<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.2.32/angular.js'></script>
<!-- including the ngCookies module here -->
<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.2.32/angular-cookies.js'></script>
<script>
// adding `ngCookies` to the dependencies
angular.module('cookieApp', ['ngCookies']).controller('MainController', ['$scope', '$cookies', function ($scope, $cookies) {
$scope.value = '';
$scope.saveCookie = function (value) {
$cookies.cap_value = value;
};
$scope.getCookie = function () {
return $cookies.cap_value;
};
}]);
</script>
</div>
</body>
</html>
I'll point out that the API changed in version 1.4, they added getters and setters. Just be aware of that, if you decide to upgrade your AngularJS version at some point in the future.

AngularJS Webpage Can't Find Referenced Angular Module or Controller

Sorry for the possible repost, but I don't know how else to write this. I've been using this website to create a small angularJS webpage using nodeJS as well, and I've gotten to the part of separating the angular code from the view, or HTML. What I've found was that when I tried to separate them nothing worked any more.
Here's my code so far:
Home.html:
<!DOCTYPE html>
<html lang="en-US">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<!-- <script>
var myApp = angular.module('myApp', []).controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
$scope.myColor = "red";
});
</script> -->
</head>
<body>
<!-- <script>
myApp.directive('myDirective', function() {
return {
template: "This is a test directive."
};
})
</script> -->
<h2>myApp Test</h2>
<div ng-app="myApp" ng-controller="myCtrl" ng-init="quantity = 10; cost = 5">
<p>Color: <input type="text" style="background-color:{{myColor}}" ng-model="myColor" value="{{myColor}}"></p>
<p>Total in dollar (raw exp): {{quantity * cost}}</p>
<p>Total in dollar (span): <span ng-bind="quantity * cost"></span></p>
<p> First Name: <input type="text" ng-model="firstName"></p>
<p> Last Name: <input type="text" ng-model="lastName"></p>
<h1>Hello, {{firstName + " " + lastName}}</h1>
</div>
Are you even changing?!
</body>
<script type="javascript" src="../JS/myApp.js"></script>
<!-- <script type="javascript" src="../JS/myApp.module.js"></script> -->
<script type="javascript" src="../JS/myCtrl.js"></script>
<!-- <script type="javascript" src="../JS/myCtrl.component.js"></script> -->
</html>
myApp.js / myApp.module.js:
var myApp = angular.module('myApp', []);
myCtrl.js / myCtrl.component.js:
myApp.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
$scope.myColor = "red";
});
// app.directive('myDirective', function() {
// return {
// template: '<p><h3>This is a test directive.<h3></p>'
// };
// });
Finally, here's my folder hierarchy:
If what I've done wrong is already evident, there's no need for you to continue reading.
Now the commented-out code is important as well. These are both the other things I've tried, and what I wanted to implement. I have tried:
Re-adding all the angular code back to the head tag to make sure it was still working at all. It worked, aside from the directive stuff (which, at point, I believe would have to be part of a separate module, but not the point, nonetheless).
Moving the script references, which are, and were, located below the body, to the head.
Moving the script references to the top of the body.
Moving everything into just *one* file (myApp.module.js).
Renaming both "myCtrl.component.js" and "myApp.module.js" to "myCtrl.js" and "myApp.js", respectively, to ensure possibly-antiquated angularJS nomenclature wasn't an attribution.
Adding "type="javascript"" to the script references.
"Hard refreshing" to make sure old documents weren't cached.
Tested to see if it was even requesting the files from the server using node. It doesn't look like it is.
If you need the nodeJS part of it, it's here as well (index.js):
var http = require('http');
var url = require('url');
var fs = require('fs');
var path = require('path');
http.createServer(function(req, res) {
var myUrl = url.parse(req.url);
var basename = path.basename(myUrl.path);
console.log('request url: ' + req.url);
console.log('url path: ' + myUrl.path);
console.log('basename: ' + basename);
fs.readFile('../HTML/Home.html', function(err, data) {
res.writeHead(200, { 'ContentType': 'text/html' });
res.write(data);
res.end();
});
}).listen(8080);
The problem is in your script tag
<script type="javascript" src="../JS/myCtrl.js"></script>
It should not be
type="javascript"
Either change it to
type="text/javascript"
or remove the type totally. Due to incorrect type , it is not loading controller and other js files to browser.

error with the injection angular.js

I have an error with my injection in the controller using angular.js
and I know that this is my problem because when I removed ngCookie the error on my console disappeared.
I have read on the web that it is ok the way i'm trying to do it - but for some reason the problem won't go away.
I tried changing the order of ngCookies and ngRoute, tried to write only one of them but I need them both, tried to change my version of angular - but still nothing work.
here is my controller
var mymedical = angular.module("mymed",['ngRoute','ngCookies']);
mymedical.controller('getPersonalCtrl',['$scope','$http',function($scope,$http) {
$http.get("http://localhost:3000/privateData").success(function(data){
$scope.insertDataToDB = data;
console.log(data);
});
}]);
mymedical.controller('insertPersonalCtrl',['$scope','$http',function($scope,$http){
var data = {};
data.email = $scope.email;
data.Tags = $scope.Tags;
data.title = $scope.title;
data.Info = $scope.Info;
data.Category = $scope.Category;
data.file = $scope.file;
data.Recommendation = $scope.Recommendation;
}]);
mymedical.controller('loginCtrl',['$scope','$http','$cookies', function($scope,$http,$cookies){
var user = {};
console.log("i'm in the controller of login");
//user.email = $scope.
//console.log($scope.email);
user.email=$scope.myemail;
user.pass = $scope.pass;
$scope.putCoockie = function(value){
var cook=$cookies.get('cookieEmail');
$cookies.put('cookieEmail',value);
console.log(value);
}
$http.post('http://localhost:3000/getUser', user).then()
}]);
how can I solve this?
Make sure you are loading the correct reference of ngCookies,
<link rel="stylesheet" href="style.css" />
<script src="//code.angularjs.org/1.2.14/angular.js"></script>
<script src="//code.angularjs.org/1.2.13/angular-route.js"></script>
<script src="//code.angularjs.org/1.2.9/angular-cookies.js"></script>
<script src="app.js"></script>
DEMO
Make sure you include ng cookies after ng route in your html page.
I am using the following in my demo project and it is working like charm.
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-route.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0/angular-cookies.min.js"></script>
Also, can you show us the error in console?

How to compile dynamic template from outside of angular?

I want to load dynamic HTML content via AJAX, then compile it, because it contains angular directives.
I have this class that uses methods that help using angular without being in the scope of an angular controller or directive:
var AngularHelper = (function () {
var AngularHelper = function () { };
/**
* ApplicationName : Default application name for the helper
*/
var defaultApplicationName = "MyApp";
/**
* Compile : Compile html with the rootScope of an application
* and replace the content of a target element with the compiled html
* #$targetDom : The dom in which the compiled html should be placed
* #htmlToCompile : The html to compile using angular
* #applicationName : (Optionnal) The name of the application (use the default one if empty)
*/
AngularHelper.Compile = function ($targetDom, htmlToCompile, applicationName) {
var $injector = angular.injector(["ng", applicationName || defaultApplicationName]);
$injector.invoke(["$compile", "$rootScope", function ($compile, $rootScope) {
//Get the scope of the target, use the rootScope if it does not exists
var $scope = $targetDom.html(htmlToCompile).scope();
$compile($targetDom)($scope || $rootScope);
$rootScope.$digest();
}]);
}
return AngularHelper;
})();
Then I use it after my jQuery successful ajax request:
<!DOCTYPE html>
<html>
<head>
<title>AngularJS Test</title>
</head>
<body>
<div id="contents"><!-- content --></div>
<script src="js/angular.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.get( "http://fuiba.com/test/index.html", function( data ) {
$("#result").html(data);
AngularHelper.Compile('$("#result")', data);
});
});
</script>
</body>
</html>
But I get this error (see this codepen):
$targetDom.html is not a function
You need to pass a DOM element not a string as a first parameter in AngularHelper.Compile function,
so
AngularHelper.Compile($("#result"), data);
not
AngularHelper.Compile('$("#result")', data);

How to display user profile information in a modal?

I have a table of registered users and would like to display their profile info in a modal
triggered by clicking on their <a href="#">name<a>.
Below is part of the working code via my Plunker
As in my code above, I'm currently doing the modal using Bootstrap, however I'm converting a lot
of our project to Angular JS. Any JS coders familiar with how to do this?
Thanks in advance
Darold
I don't know if this will answer your question but I have created a plunker demo using AngularJS
http://plnkr.co/edit/bNzolsIIm5geRd05Jaq6
HTML File code
<!DOCTYPE html>
<html ng-app="angularjs-starter">
<head lang="en">
<meta charset="utf-8">
<title>Dynamic User Profile Loading</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
<link rel="stylesheet" href="style.css">
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<table >
<tr ng-repeat="user in users">
<td><a ng-click="getUserProfile(user)">{{user.username}}</a></td>
<td>{{user.profile.fullName}}</td>
<td>{{user.profile.email}}</td>
<td>{{user.profile.phone}}</td>
</tr>
</table>
</body>
</html>
Javascript Code
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope) {
$scope.users =[{username: 'first'},{username: 'second'}, {username: 'third'},{username: 'fourth'}];
$scope.getUserProfile = function(user){
//Here we have received the user object so search for the object int he array
var inx = $scope.users.indexOf(user);
if(inx >= 0)
{
//retrieve user profile from server.
//Here we are going to set some values for the demo purpose
$scope.users[inx].profile = {}; //Initialize profile as an object
$scope.users[inx].profile.fullName = user.username + ' user';
$scope.users[inx].profile.email = user.username + '#example.com';
$scope.users[inx].profile.phone = user.username + ' phone';
}
};
});
I blogged about this a couple weeks ago. My blog post includes a plunkr example of doing pretty much exactly this with a twitter bootstrap modal (and no extra UI directives)
http://willvincent.com/blog/angularjs-and-twitter-bootstrap-playing-nicely

Categories