$http.get error in angular and node - javascript

My problem is $http.get instruction --> Without $http.get in the main page I get "random 46" (test ok) but if I insert $http.get I get "random {{ number }}".
How can I fix this?
-server.js
-public
-core.js
-index.html
server.js (node backend)
//restful api
app.get('/api/random', function(req, res) {
res.json({
"text" : "4"
});
});
//app
app.get('*', function(req, res) {
res.sendFile(__dirname + '/public/index.html');
});
core.js (angular frontend)
angular.module("myModule", [])
.controller('myController', function($scope) {
$scope.number = 46;
$http.get('/api/random')
.then(function successCallback(res) {
$scope.number = res.data;
console.log('success');
}, function errorCallback() {
console.log('Error');
});
})
index.html
<html ng-app="myModule">
<head>
<!-- META -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"><!-- Optimize mobile viewport -->
<title>Random number from sa-mp</title>
<!-- SCROLLS -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"><!-- load bootstrap -->
<style>
html { overflow-y:scroll; }
body { padding-top:50px; }
#todo-list { margin-bottom:30px; }
</style>
<!-- SPELLS -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script><!-- load jquery -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script><!-- load angular -->
<script src="core.js"></script>
</head>
<!-- SET THE CONTROLLER AND GET ALL TODOS -->
<body ng-controller="myController">
<div class="container">
<!-- HEADER AND TODO COUNT -->
<div class="jumbotron text-center">
<h1>random <span class="label label-info">{{ number }}</span></h1>
</div>
</div>
</body>
</html>
EDIT:
I tried
res.data
$scope.$apply();
and
res.data.text
$scope.$apply();
and
res.text
$scope.$apply();
but it didn't work.
EDIT 2: RESOLVED
I replaced this
.controller('myController', function($scope) {
with
.controller('myController', function($scope, $http) {
and used this to set data
$scope.number = res.data.text;

Try to use $scope.$apply() at the last line of your callback.
like:
$http.get('/api/random')
.then(function successCallback(res) {
$scope.number = res.data.text;
$scope.$apply();
console.log('success');
}, function errorCallback() {
console.log('Error');
});
If it works. You can know more about that in this article: http://jimhoskins.com/2012/12/17/angularjs-and-apply.html
Also, you should get res.data.text to have the right value on your html. like: $scope.number = res.data.text;

Related

In AngularJS, loaded content by ui-view cannot read javascript file in parent content

I want to insert header and nav bar into index.html
When header and nav bar are in index.html, My app works well.
but seperate these files to html and try to load, ui-view do not load script files.
So logout function does not work when ui-view loaed header.html
On the other hand, css works well.
I tried to follow answers like
Angularjs does not load scripts within ng-view
or
html partial is not loaded into ui-view
but it did not help to fix my problem..
Why this situation occurred?
Please any handsome or pretty developer help me..
These are my code.
app.js
'use strict';
var mainApp = angular
.module('adminApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch',
'ui.router'
]);
mainApp.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/admin/login');
$stateProvider
.state('root',{
url: '',
abstract: true,
views: {
'headerContainer': {
templateUrl: 'views/header.html',
controller: 'HeaderCtrl',
controllerAs: 'header'
},
'navContainer':{
templateUrl: 'views/nav.html',
controller: 'NavCtrl',
controllerAs: 'nav'
}
}
})
.state('root.login', {
...
})
});
index.html
<!DOCTYPE html>
<html ng-app="adminApp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Admin</title>
<base href="/">
<!-- CSS-->
<link href="bower_components/bootstrap/dist/css/main.css" rel="stylesheet">
<!-- Font-icon css-->
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<!-- start: Favicon -->
<link href="favicon.ico" rel="shortcut icon">
<!-- end: Favicon -->
</head>
<body class="sidebar-mini fixed" ng-controller="AppCtrl">
<div class="wrapper">
<div ui-view="headerContainer"></div>
<div ui-view="navContainer"></div>
<div ui-view="appContainer"></div>
</div>
<!-- Javascripts-->
<script src="../bower_components/bootstrap/dist/js/jquery-2.1.4.js"></script>
<script src="../bower_components/angular/angular.js"></script>
<script src="../bower_components/bootstrap/dist/js/bootstrap.js"></script>
<script src="../bower_components/angular-animate/angular-animate.js"></script>
<script src="../bower_components/angular-cookies/angular-cookies.js"></script>
<script src="../bower_components/angular-resource/angular-resource.js"></script>
<script src="../bower_components/angular-route/angular-route.js"></script>
<script src="../bower_components/angular-sanitize/angular-sanitize.js"></script>
<script src="../bower_components/angular-touch/angular-touch.js"></script>
<script src="../bower_components/angular-ui-router/release/angular-ui-router.js"></script>
<script src="../bower_components/bootstrap/dist/js/main.js" ></script>
<script src="scripts/app.js"></script>
<script src="scripts/controllers/headerCtrl.js"></script>
<script src="scripts/controllers/navCtrl.js"></script>
</body>
</html>
header.html
<header class="main-header hidden-print">
<nav class="navbar navbar-static-top">
<div class="navbar-custom-menu">
<ul class="top-nav">
<li>
<a ng-click="logout();">Logout</a>
</li>
</ul>
</div>
</nav>
</header>
headerCtrl.js
mainApp.controller('HeaderCtrl', function ($scope, $cookieStore) {
$scope.logout = function () {
angular.forEach($cookies.getAll(), function (v, k) {
$cookies.remove(k);
}); // This is for remove all cookies
};
});
main.js
$('.top-nav li a').on('click', function (e) {
console.log('Clicked header li');
});
It seems like you haven't used controller alias while calling logout method
ng-click="header.logout();"
As #pankaj said you need to declare the logout method on your controller alias
ng-click="header.logout();"
And the same applies for your js. You have to reference logout with this keyword since you are using controller as syntax
mainApp.controller('HeaderCtrl', function ($scope, $cookieStore) {
var vm =this;
vm.logout = function () {
angular.forEach($cookies.getAll(), function (v, k) {
$cookies.remove(k);
}); // This is for remove all cookies
};
});
For more Info: AngularJs "controller as" syntax - clarification?

$http GET not showing in display in AngularJS

I am creating an app in AngularJS, where I am grabbing the data from the backend to display on the view. But, for some reason, I am getting the data in my console but not in my view. I will be so thankful if any one can help me solve this. Thanks in advance.
Here is my code. -Services
app.factory('user', ['$http', function($http) {
var userInfo = {
getUserInfo: function () {
return $http.get('https://************/*****/**/***********')
}
};
return userInfo;
}]);
home page(view)
<div class="users" ng-repeat="user in users | filter:userSearch" >
<a href="#/users/{{ user.id }}">
<img ng-src="{{user.img}}"/>
<span class="name">{{user.first}} </span>
<span class="name">{{user.last}} </span>
<p class="title">{{user.title}} </p>
<span class="date">{{user.date}} </span>
</a>
HomeController
var isConfirmed = false;
app.controller('HomeController', function($scope, user, $http) {
if (!isConfirmed) {
user.getUserInfo().then(function (response) {
$scope.userInfo = response.data;
isConfirmed = $scope.userInfo;
console.log($scope.userInfo);
}, function (error) {
console.log(error)
});
}
});
App.js
var app = angular.module("Portal", ['ngRoute']);
app.controller('MyCtrl', function($scope) {
$scope.inactive = true;
$scope.confirmedAction = function() {
isConfirmed.splice($scope.person.id, 1);
location.href = '#/users';
}
});
index.html
<!doctype html>
<html ng-app="Portal">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="https://code.angularjs.org/1.2.28/angular-route.min.js"></script>
<link href='https://fonts.googleapis.com/css?family=Roboto:400,300,700' rel='stylesheet' type='text/css'>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link href="css/main.css" rel="stylesheet" />
</head>
<body>
<div class="header">
<div class="container">
<h3>Portal</h3>
</div>
</div>
<div class="main">
<div class="container">
<div ng-view>
</div>
</div>
</div>
<!-- Modules -->
<script src="js/app.js"></script>
<!-- Controllers -->
<script src="js/controllers/HomeController.js"></script>
<script src="js/controllers/UserController.js"></script>
<!-- Services -->
<script src="js/services/users.js"></script>
</body>
</html>
change your ng-repeat="user in users" to ng-repeat="user in userInfo"
as your assigning and consoling only $scope.userInfo in your controller
The property you assign data has to be same as of binded to view.
As per your HTML data should be in users. So do it like : $scope.users = response.data;.
or if you assign data to userInfo, then bind it on html. like :
<div class="users" ng-repeat="user in userInfo | filter:userSearch" >

Trouble initializing AngularJS Controller: Cannot set property ... of undefined

I'm new to angular and working on a small project which has multiple modules loaded onto a single page as requested. Currently I'm just trying to get the application to load a parameter with the staffdetails.html module and update it with the controller. Currently it just displays
Hello
Staff Details....
{{testing}}
So the value from the controller is not being loaded. I've tried in both angular 1.2 legacy and 1.5.9 (I think the latest stable), as I know syntax has apparently changed.
Here is the index.html page.
<!-- index.html -->
<!DOCTYPE html>
<html ng-app="app">
<head>
<!-- SCROLLS -->
<!-- load bootstrap and fontawesome via CDN -->
<link rel="stylesheet" type="text/css" src="lib/bootstrap.min.css" />
<!-- SPELLS -->
<!-- load angular and angular route via CDN -->
<script src="lib/angular.min.js"></script>
<script src="lib/angular-ui-router.min.js"></script>
<script src="lib/jquery-2.1.1.min.js"></script>1
<script>
(function() {
angular.module("app", ["ui.router"]);
}());
</script>
<!-- Services -->
<!--script src="app/service/informationStorage-Service.js"</script-->
<!-- Controllers -->
<script src="app/controller/additionalfeatures-controller.js"></script>
<script src="app/controller/outcome-controller.js"></script>
<script src="app/controller/staffdetails-controller.js"></script>
<script src="app/controller/training-controller.js"></script>
<script>
$(document).ready (
function () {
var app = angular.module("app");
console.log("Index1");
app.config(["$stateProvider", "$urlRouterProvider", "$compileProvider", function ($stateProvider, $urlRouterProvider, $compileProvider) {
//$compileProvider.debugInfoEnabled(false);
$stateProvider.state(
"staffdetails", {
url: "/staffdetails",
views: {
"": {
templateUrl: "template/staffdetails.html",
controller: "StaffDetailCtrl"
}
}
}
);
console.log("Index2");
$urlRouterProvider.otherwise("");
} ]);
} ());
</script>
</head>
<body>
Hello
<!-- MAIN CONTENT AND INJECTED VIEWS -->
<div id="main">
<div ui-view ng-cloak></div>
</div>
</body>
staffdetails-controller.js
(function() {
"use strict";
var app = angular.module("app");
app.controller('StaffDetailCtrl', ['$scope', function($scope) {
console.log("StaffDetailCtrl");
function saveDetails($scope) {
$scope.testing = ["This is Working"];
};
saveDetails();
}]);
});
Finally the page which is being called as a module
<div class="container">
<p>Staff Details...</p>
<p> {{testing}} </p>
</div>
The problem is you are not passing the $scope into your saveDetails() function.
I modified your code slightly so it would work here in a snippet. But, the main change was this line:
saveDetails($scope);
See working snippet here:
<!-- index.html -->
<!DOCTYPE html>
<html ng-app="app">
<head>
<!-- SCROLLS -->
<!-- load bootstrap and fontawesome via CDN -->
<link rel="stylesheet" type="text/css" src="lib/bootstrap.min.css" />
<!-- SPELLS -->
<!-- load angular and angular route via CDN -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.js"></script>
<script src="//unpkg.com/angular-ui-router/release/angular-ui-router.min.js"></script>
<!-- Controllers -->
<script>
angular.module("app", ["ui.router"]);
var app = angular.module("app");
app.controller('StaffDetailCtrl', ['$scope', function($scope) {
console.log("StaffDetailCtrl");
function saveDetails($scope) {
$scope.testing = ["This is Working"];
}
saveDetails($scope);
}]);
console.log("Index1");
app.config(["$stateProvider", "$urlRouterProvider", "$compileProvider", function ($stateProvider, $urlRouterProvider, $compileProvider) {
//$compileProvider.debugInfoEnabled(false);
$stateProvider.state(
"staffdetails", {
url: "/staffdetails",
views: {
"": {
template: '<div class="container">' +
'<p>Staff Details...</p>' +
'<p> {{testing}} </p>' +
'</div>',
controller: "StaffDetailCtrl"
}
}
}
);
console.log("Index2");
$urlRouterProvider.otherwise("/staffdetails");
} ]);
</script>
</head>
<body>
Hello
<!-- MAIN CONTENT AND INJECTED VIEWS -->
<div id="main">
<div ui-view ng-cloak></div>
</div>
</body>

Uncaught ReferenceError: app is not defined in controller, module, and route

Trying to make a crud app with ionic. But when I run my app, it can't show data. The error is:
Uncaught ReferenceError: app is not defined
at http://localhost:8100/controller/controller.js:1:1
Uncaught ReferenceError: app is not defined
at http://localhost:8100/controller/edit.js:1:1
Uncaught ReferenceError: app is not defined
at http://localhost:8100/js/route.js:1:1
Uncaught Error: [$injector:modulerr] Failed to instantiate module
myAPP due to:(…)
Can anyone help me please?
index :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link rel="manifest" href="manifest.json">
<!-- un-comment this code to enable service worker
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('service-worker.js')
.then(() => console.log('service worker installed'))
.catch(err => console.log('Error', err));
}
</script>-->
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
</head>
<body ng-app="myAPP">
<ion-pane>
<ion-header-bar class="bar-stable">
</ion-header-bar>
<ion-content>
<div class="tabs-striped tabs-top">
<div class="tabs">
<a class="tab-item" href="#/">List</a>
<a class="tab-item" href="#/addData">Add Data</a>
<a class="tab-item" href="#/editData">Edit Data</a>
</div>
</ion-content>
<div class="container">
<h2>{{title}}</h2>
</br>
</br>
<table class="table table-striped" ng-init="getData()">
<tr>
<th>NO</th>
<th>Nama</th>
<th>Alamat</th>
<th>Action</th>
</tr>
<tr ng-repeat="x in dataList">
<td>{{$index+1}}</td>
<td>{{x.nama}}</td>
<td>{{x.alamat}}</td>
<td>
<button type="button" class="btn btn-info" ng-click="edit(x.id)">Edit</button>
<button type="button" class="btn btn-danger" ng-click="delete(x.id)">Delete</button>
</td>
</tr>
</table>
</div>
<script src="js/angular.js"></script>
<script src="js/angular-route.js"></script>
<script src="js/app.js"></script>
<script src="controller/controller.js"></script>
<script src="controller/edit.js"></script>
<script src="js/route.js"></script>
</ion-pane>
</body>
</html>
controller :
app.controller("controller",['$scope','$http', function($scope,$http){
console.log('hello world');
$scope.title = 'Data List';
$scope.action = "add";
$scope.listData = {};
$scope.dataList;
$scope.getData = function(){
$http.get(
'/data/getdata.php'
).success(function(data){
$scope.dataList = data;
});
};
$scope.delete = function(id){
$http.post(
'/data/delete.php',
{
id:id
}
).success(function(){
$scope.getData();
}).error(function(){
alert("Gagal");
});
};
$scope.add = function(){
$http.post(
'/data/add.php',
{
data: $scope.listData
}
).success(function(data){
//alert(data);
$scope.action = "add";
$scope.getData();
window.location.href = 'index.html';
}).error(function(){
alert("Gagal menyimpan data");
});
};
$scope.edit = function(index){
//var index = getSelectedIndex($index);
window.location.href = '#/editData/'+index;
// $scope.listData.nama = $scope.dataList[index].nama;
// $scope.listData.alamat = $scope.dataList[index].alamat;
}
function getSelectedIndex($index){
for (var i = 0; i < $scope.listData.length; i++) {
if($scope.listData[i].index===index);
return i;
}
return -1;
}
}]);
route :
app.config(['$routeProvider',function($routeProvider){
$routeProvider.
when('/',{
templateUrl : '/pages/list.html',
controller : 'controller'
})
.when('/addData',{
templateUrl : '/pages/addData.html',
controller : 'controller'
})
.when('/editData/:id',{
templateUrl : '/pages/update.html',
controller : 'controllerEdit'
})
.otherwise({
redirectTo : '/'
});
}]);
module :
var app = angular.module('myAPP', ['ionic'],['ngRoute'])
i think missing ng-controller="myctrlname" directive inside of html.
<body ng-app="myAPP" ng-controller="myctrlname">
Your module declaration is wrong. It should be like this
angular.module('myAPP', ['ionic','ngRoute'])
The variable named app will not exist unless you create it. Once the module has been created in your module file, you can retrieve it at the top of your other files like this:
var app = angular.module('myAPP');
I faced same problem
then
Only removed 'starter.controllers'
var app = angular.module('starter', ['ionic', 'starter.controllers']);
replace with
var app = angular.module('starter', ['ionic']);

AngularJS dynamically load template and js file

I want to dynamically add menu JavaScript file and html to content.html, but it can't do.
I created simple example
demo
I try move "<script src="menu.js"></script>" to menu.html
Your code moves away from the whole idea of writing single page app with angular. I have updated it to give you basic idea of how you would do the routes and share templates and use controller.
Check out the plunkr
html
<html>
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<link rel="stylesheet" href="menu.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.8/angular.js" data-semver="1.4.8"></script>
<script data-require="ui-router#*" data-semver="0.2.15" src="https://cdn.rawgit.com/angular-ui/ui-router/805e69bae319e922e4d3265b7ef565058aaff850/release/angular-ui-router.js"></script>
<script src="menu.js"></script>
<script src="index.js"></script>
</head>
<body>
<div id="menu" ng-include="'menu.html'"></div>
<div ui-view></div>
</body>
</html>
js
angular.element(document).ready(function() {
angular.bootstrap(document, ["app"]);
});
angular.module('app',['moduleContent', 'moduleMenu', 'ui.router']);
var app = angular.module('app');
app.config(function($stateProvider) {
$stateProvider
.state('index', {
url: "",
templateUrl: "first.html",
controller: 'firstCtrl'
})
.state('second', {
url: "/second",
templateUrl: "second.html"
})
});
app.controller('firstCtrl', ['$scope', function($scope) {
$scope.page = "first";
}]);
//Conttent module
angular.module('moduleContent',[])
.controller('contentCtrl', contentCtrl);
function contentCtrl(shareData)
{
shareData.currentPage = 0;
}

Categories