Angular JS route, http and json strange works - javascript

I am a newbie in Angular JS. I am replacing a webapp from jquery and PHP to Angular JS + PHP (PHP is necessary to get data from DB and pass it on JSON).
The PHP module works, I have tested. My problem is on AngularJS.
This is index.html
<body ng-app="manager">
<div class="container">
<nav class="navbar navbar-default">
<div class="container-fluid" ng-controller="managerController as menuManager">
<div class="navbar-header">
<a class="navbar-brand" href="#">Manager</a>
</div>
<ul class="nav navbar-nav">
<li class="active" ng-repeat="voce in menuManager.voce">{{voce.nome}}</li>
</ul>
</div>
</nav>
<div ng-view></div>
</div>
</body>
This is manager.js
var app = angular.module('manager', ['ngRoute']);
app.config(['$routeProvider',
function($routeProvider){
$routeProvider
.when("/a",{templateUrl:"a.html",controller:"aCtrl"})
.when("/b",{templateUrl:"b.html",controller:"bCtrl"})
.when("/c",{templateUrl:"c.html",controller:"cCtrl"})
.when("/d",{templateUrl:"d.html",controller:"dCtrl"}); }]);
app.controller('managerController',function(){
this.voce = menu;
});
menu = [
{'nome':'A', 'url':'a'},
{'nome':'B', 'url':'b'},
{'nome':'C', 'url':'c'},
{'nome':'D', 'url':'d'}
];
This is the aCtrl.js
app.controller("aCtrl", function($http,$scope){
$http.post("../../qry_select.php",{"payload":"manager"})
.success(function(data){
alert("Work!");
$scope.content = data;
})
.error(function(){
alert ("Doesn't work");
});
});
and this is the aView.html
<div ng-controller="aCtrl">
<p>{{content}}</p>
</div>
My problems are:
Work alert is showed twice (?)
Content is blank
Firebug shows me just qry_select.php send data, not received data
Please help me

Related

Angular Routing - Load data into parent page before first route

I am using angular routing for a admin panel project. Following is my angular js code.
app.js
(function() {
var app = angular.module("app", [
"ngRoute",
"app.dashboard",
"app.calendar",
"app.event"
]);
var dashboard = angular.module("app.dashboard");
dashboard
.config(function($routeProvider) {
$routeProvider.
when('/dashboard', {
templateUrl: '/views/dashboard/dashboard.html',
controller: 'DashBoardIndexController as ctrl'
}).
when('/dashboard/detail', {
templateUrl: "/views/dashboard/detailgraph.html",
controller: "DashBoardDetailController as ctrl"
})
});
......
......
//Controllers related to dashboard module
var calendar = angular.module("app.calendar");
calendar
.config(function($routeProvider) {
$routeProvider.
when('/calendar', {
templateUrl: '/views/calendar/calendar.html',
controller: 'CalendarIndexController as ctrl'
}).
when('/calendar/markevent', {
templateUrl: "/views/calendar/markevent.html",
controller: "CalendarEventController as ctrl"
})
});
......
......
//Controllers related to calendar module
}());
For better code management, I am dividing various module of application and including them in main app module.
After login, the first route loaded will be of dashboard (/dashboard). But before route provider initialized and dashboard loaded, I need to fetch the user's rights level and accordingly create the side navigation menus in parent page. Below is my parent page:
home.html
<body ng-app="app">
<header>
<nav id="mynav" class="bold z-depth-1" role="navigation">
<div class="nav-wrapper container">
<a id="logo-container" href="#" class="brand-logo text-darken-1">Logo</a>
<div class="container">
<a href="#" data-activates="slide-out" class="button-collapse top-nav full hide-on-large-only black-text"><i
class="mdi-navigation-menu"></i></a>
</div>
</div>
</nav>
<ul id="slide-out" class="side-nav fixed center-align">
<!-- This side menu items should be created based on user's rights --!>
</ul>
</header>
<main class="grey lighten-4">
<div id="main-container" class="container z-depth-1 ">
<div ng-view=""></div>
</div>
</main>
As you can see, before ng-view is loaded with first route (/dashboard), I need to make server call to fetch the user's rights. I am relatively new to angular and I think we can do this by resolve promise. But here two modules are different (app and app.dashboard).
What could be the correct way to solve this problem?

Angular1.3: Access functions from standard controllers, inside a view which uses controllerAs?

I have a simple controller defined in my main app.js file, which controls opening/closing of my navbar and is visible on all other views of my app:
app.js:
.controller('mainController', ['$scope', function($scope){
$scope.menuActive = false;
$scope.toggleMenu = function(){
$scope.menuActive = !$scope.menuActive;
}
}]);
index.html:
<nav class="side-menu" ng-class="{ 'side-menu-open' : menuActive }">
<ul>
<li>LINK1</li>
<li>LINK2</li>
</ul>
</nav>
<!--Other views::.....-->
<div ui-view></div>
All my other views(which use controllerAs), have a button with an ng-click which I am using to access the above $scope.toggleMenu() function and ng-class, but this does not work, and I don't get any errors either:
view1.html :
<span class="btn btn-default"
ng-click="toggleMenu()">
MENU
</span>
View1.js:
angular
.module('myApp.view1', [])
.controller('View1Ctrl', [
function(){
................
}
]);
Also, the reason I have done it this way again is because my navbar is persistent throughout my app. Does this go against best practices by any chance?
If you are using the .. controller as .. syntax, make sure that you are using it for all controllers. Don't be selective about it.
Next, when using the syntax, you need not inject the $scope object. You need to instead use the this variable and attach any properties or functions that you would normally associate with the $scope object with the this object instead.
Thus,
$scope.toggleMenu = function(){
$scope.menuActive = !$scope.menuActive;
}
becomes
this.toggleMenu = function(){
this.menuActive = !this.menuActive;
}
Finally in your view, be sure to associate each expression with a controller.
<div ng-controller="mainController as main">
<nav class="side-menu" ng-class="{ 'side-menu-open' : main.menuActive }">
<ul>
<li>LINK1</li>
<li>LINK2</li>
</ul>
</nav>
<div ui-view>
<!-- Assuming that the following gets compiled to ui-view -->
<span class="btn btn-default" ng-click="main.toggleMenu()">
MENU
</span>
</div>
</div>
You can get some further hints on using the controller as syntax here

update variable in another controller in AngularJS

okay, so I am building a web-app using angular.js. I have started to implement user authentication.
I did this with it's own controller:
app.controller("userControl", ["$http", "share", function($http, share){
this.login = {};
var user = this;
this.doLogin = function(){
this.login.fn = "login";
$http.post('classes/main.php', user.login).success(function(data){
console.log(data.Error);
if(data.Error == undefined){
alert("Success");
share.user = data;
window.location.href = "#memberHome";
}
});
}
}]);
and I have a member's page with it's own controller:
HTML:
<div id="memberHome" data-role="page" ng-controller="member-Ctrl as member">
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<p class="navbar-brand" href="#">Calendar</p>
</div>
<ul class="nav navbar-nav navbar-left">
<li>Overview</li>
<li>Friends</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><span class="glyphicon glyphicon-user"></span> Logged in as: {{member.user.forename + " " + member.user.surname}}</li>
<li><span class="glyphicon glyphicon-log-in"></span> Log Out</li>
</ul>
</div>
</nav>
<div data-role="content">
<calendar selected="day"></calendar>
</div>
</div>
javascript:
app.controller("member-Ctrl", ["share", function(share){
this.user=share.user;
}]);
I need the User controller to tell the member controller the details of the new user.
I googled this and looked at the answers of a similar question, which led me to This
and i created a service as shown in the video:
app.service("share", function(){
this.user = {}
});
Now whenever i login and get redirected to the memberHome page, it tells me Logged in as:
Can anybody see why this might be?
I am very new to Angular, and am learning, just about, everything when I need it.
I should probably say that i am using jQuery Mobile (for a multi-page document) and Bootstrap 3
You can use a service to share information between controllers or use the $rootScope
var app = angular.module('mymodule',[]);
app.controller('Controller1', ['$scope','$rootScope',
function($scope, $rootScope) {
$rootScope.showImages = true;
}]);
app.controller('Controller2', ['$scope','$rootScope',
function($scope, $rootScope) {
$rootScope.showImages = false;
}]);
And in the template:
<div ng-controller="Controller1">
<div class="images" ng-show="$root.showImages"></div>
</div>

Books Won't Display for Reader App Exercise

I'm trying to get books to display based on the assignment above but can't figure out what is wrong for the life of me.
I built the service and modified the controller and view pages to the point where I believe they should display the books in the view, but I'm just seeing a blank page.
I feel like I am probably not retrieving the data properly and accessing it in the view/html.
Any ideas? Link to jsFiddle.
Index.html
<body ng-app="ReaderApp">
<div class="header">
<div class="container">
Reader
</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/BookshelfController.js"></script>
<script src="js/controllers/BookController.js"></script>
<script src="js/controllers/ChapterController.js"></script>
<!-- Services -->
<script src="js/services/books.js"></script>
</body>
js/apps.js
var app = angular.module('ReaderApp', ['ngRoute']);
app.config(function($routeProvider){
$routeProvider
.when('/books', {
controller: 'BookshelfController',
templateUrl: 'views/bookshelf.html'
})
.otherwise({
redirecTo: '/books'
});
});
js/services/books.js
app.factory('books', ['$http', function($http) {
return $http.get('https://s3.amazonaws.com/codecademy-content/courses/ltp4/books-api/books.json')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
js/controllers/BookshelfController
app.controller('BookshelfController', ['$scope', 'books', function($scope, books) {
books.success(function(data) {
$scope.myBooks = data;
});
}]);
js/views/bookshelf.html
<div class="bookshelf row">
<!--
TODO: Loop through myBooks and display each one with this HTML
<div class="book col-md-3">
<a href="#/books/{{$index}}">
TODO: Add the book's cover here
<h3 class="title"> </h3>
<p class="author"> </p>
</a>
</div>
-->
<div class="book col-md-3" ng-repeat="book in myBooks">
<a href="#/books/{{$index}}">
<img ng-src="{{ book.cover }}">
<h3 class="title">{{ book.title }}</h3>
<p class="author">by {{ book.author }}</p>
</a>
</div>
</div>
I think I had the same trouble and my problem was in the router. Try adding array brackets ( [ ] ) and the '$routeProvider' string in your config method (app.js) like this:
app.config(['$routeProvider', function($routeProvider) {
// Normal router stuff goes here
}]);
Coming from Ember, the syntax is a little weird so I've been using this tutorial as reference when I get stuck.

AngularJS variables not resolving/displaying

Here is the relevant HTML:
<!DOCTYPE html>
<html ng-app="wpApp">
<body>
<div ng-controller="controllerMain as main">
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav navbar-left">
<li>Link 1</li>
<li>Link 2</li>
<li>Link 3</li>
</ul>
</div>
<!-- Start of View State -->
<div class="page-content" style="padding-left:10px; padding-right:10px">
<div ng-view></div>
</div>
<!-- End of View State -->
<div class="footer">
<div class="banner">
{{main.message}}
</div>
</div>
</div>
</body>
</html>
And here is the relevant Javascript
wpApp = angular.module("wpApp", ["ngRoute", "ngAnimate", "ui.bootstrap", "angularFileUpload"]);
wpApp.config(function($routeProvider) {
return $routeProvider.when("/", {
templateUrl: "one.html",
controller: "controllerOne"
}).when("/two", {
templateUrl: "two.html",
controller: "controllerTwo"
}).when("/three", {
templateUrl: "three.html",
controller: "controllerThree"
});
});
wpApp.controller("controllerMain", function() {
this.ready = 'true';
this.message = "This is the Main Controller";
});
});
Now, with everything set up exactly as it is above (with some additional controllers for the other pages and all), controllerMain's message is properly displayed: "This is the Main Controller" in the specified spot within the HTML.
Now, I need an $http call to be made in controllerMain, so I change it like so:
wpApp.controller("controllerMain", function($http) {
this.ready = 'true';
this.message = "This is the Main Controller";
return $http.get("config.json").success(function(data) {
console.log("Here");
});
});
When this happens, I can see "Here" in the log, but nothing is displayed where "{{main.message}}" should be displayed. A little debugging has shown me that basically if the $http GET call is made, nothing is displayed. If I remove the call, the message displays.
What is the problem here? Is it something with the way the program is configured? Am I not understanding something about the way controllers work?
please try to remove the return you don'e need to return anything from the controller
wpApp.controller("controllerMain", function($scope, $http) {
$scope.ready = 'true';
$scope.message = "This is the Main Controller";
$http.get("config.json").success(function(data) {
console.log("Here");
});
});
I also suggest to use $scope.message = "This is the Main Controller";
and on html {{message}}

Categories

Resources