Angular ui-router resolve http empty value - angularjs

I'm testing a simple angular application and I'm facing some problems. The http GET call is done but resolver renders empty. Here is the code :
A simple index.html :
<html ng-app="myApp">
<head>
//all scripts loaded
</head>
<body ng-controller="myCtrl">
<p>{{test}}</p>
<a ui-sref="tab1">Show Tab 1</a>
<a ui-sref="tab2">Show Tab 2</a>
<a ui-sref="tab3">Show Tab 3</a>
<ui-view></ui-view>
</body>
</html>
The app.js :
var app = angular.module('myApp', ['ui.router']);
app
.service('DataService', function ($http) {
return {
getData: function() {
return $http({
method : "GET",
url : "/hi"
}).then(function(response) {
return response.data;
},function(response) {
return "error";
});
}
}
});
app
.controller('myCtrl', function($scope) {
$scope.test = "Test";
});
app
.config(function($stateProvider, $urlRouterProvider){
$stateProvider
.state('tab1', {
url: '/tab1',
templateUrl: '/assets/templates/tab1.html'
})
.state('tab2', {
url: '/tab2',
templateUrl: '/assets/templates/tab2.html'
})
.state('tab3', {
url: '/tab3',
templateUrl: '/assets/templates/tab3.html'
resolve:{
mydata : function (DataService) {
return DataService.getData();
}
},
controller: 'myCtrl'
});
$urlRouterProvider.otherwise('/tab1');
});
Tab3 template :
<p>Data: {{mydata}}</p>
As I said, when I click the "tab3" link, the http get call is done, and a JSON data is retrieved, but "mydata" is rendered to blank.
Any clue??
Thanks and regards.

Your controller doesn't do anything with mydata. So it's not in the scope, so the view can't display it. It should be:
app.controller('myCtrl', function($scope, mydata) {
$scope.mydata = mydata;
});

Related

Redirect to other view with controller method and routh

i want when user click on someone user ,show new view for that information.
I have two controlles,first get list of user,and it is work fine,but second controller have function which hava param of users id,but they show blank page.I realy don t know how to redrect view from second controller method.
This is my code:
<html>
<head>
<title>Angular JS Views</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular-route.js"></script>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app = "app">
<p>view Students</p>
<p>View Student</p>
<div ng-view></div>
<script type = "text/ng-template" id = "viewStudents.htm">
<ul ng-repeat="entry in pacijenti">
<li>{{ entry.ime }}</li>
<li>{{entry.prezime}}</li>
<li>{{entry.jmbg}}</li>
<button type="button" ng-click="getP(entry.jmbg)" >
</button>
<a ng-href='#viewStudent' ng-click="myCtrl.getP(entry.jmbg)" >click me</a>
</ul>
</script>
<script type = "text/ng-template" id = "viewStudent.htm">
<ul ng-repeat="entry2 in pac">
<li>{{entry2.dijagnoza}}</li>
<li>{{entry2.bolest}}</li>
link1
</ul>
</script>
</div>
<script>
var app = angular.module("app", ['ngRoute']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/viewStudents', {
templateUrl: 'viewStudents.htm',
controller: 'HomeController'
}).
when('/viewStudent', {
templateUrl: 'viewStudent.htm',
controller: 'myCtrl'
}).
otherwise({
redirectTo: '/viewsStudents'
});
}]);
app.factory('photos', ['$http', function($http) {
return $http.get("http://localhost:8080/mavenproject2/fizijatar/12345/pacijenti")
.success(function(response) {
return response;
})
.error(function(response) {
return response;
});
}]);
app.controller('HomeController', ['$scope', 'photos', function($scope, photos) {
$scope.pacijenti=this;
photos.success(function(response) {
$scope.pacijenti =response;
});
}]);
app.controller('myCtrl', function($scope, $http) {
$scope.pac=this;
$scope.getP=function(jmbg){
$http.get("http://localhost:8080/mavenproject2/fizijatar/12345/pacijenti/"+jmbg+"/pregledi")
.then(function(response) {
$scope.pac = response.data;
}, function(response) {
$scope.pac = "Something went wrong";
});
};
});
</script>
</body>
</html>
Modify your route to accept a jmbg id:
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/viewStudents', {
templateUrl: 'viewStudents.htm',
controller: 'HomeController'
}).
when('/viewStudent/:jmbg', {
templateUrl: 'viewStudent.htm',
controller: 'myCtrl'
}).
otherwise({
redirectTo: '/viewsStudents'
});
}]);
Then in the controller, retrieve the jmbg id:
app.controller('myCtrl', function($scope, $http, $routeParams) {
$scope.pac = this;
$scope.jmbg = $routeParams.jmbg;
$scope.getP = function(jmbg){
$http.get("http://localhost:8080/mavenproject2/fizijatar/12345/pacijenti/"+jmbg+"/pregledi")
.then(function(response) {
$scope.pac = response.data;
}, function(response) {
$scope.pac = "Something went wrong";
});
// Call the getP function with the jmbg id
$scope.getP($scope.jmbg);
};
});
The link to open the student view would look like this:
<a ng-href="#viewStudent/{{entry.jmbg}}">click me</a>
Here is a working plunker example: https://plnkr.co/edit/99aDJkuvIDopNoILNFGB?p=preview -- Please note, I removed the photo factory usage, and instead hard coded example data.

How do i navigate one page to another in angularjs

i tried to navigate one page to another page but it didn't work.i used angularjs as front end.
My angularjs file is
var app = angular.module('loginApp', ['ui.router']);
app.config(function($stateProvider, $urlRouterProvider) {
// default route
$urlRouterProvider.otherwise("/");
// app routes
$stateProvider
.state('home', {
url: '/tokken/s/',
templateUrl: 'templates/register.html',
controller: 'loginCtrl'
});
});
// Controller function and passing $http service and $scope var.
app.controller('loginCtrl', function($scope, $state, $http) {
// create a blank object to handle form data.
$scope.user = {};
// calling our submit function.
$scope.submitForm = function() {
// Posting data to file
$http.post('/tokken/login/', $scope.user).then(function (response) {
//$httpProvider.defaults.headers.common["X-AUTH-TOKEN"] = response.data;
if (response.errors) {
// Showing errors.
$scope.errorName = response.errors.name;
$scope.erroPassword = response.errors.password;
} else {
//$scope.message = response.data;
$state.go('home');
}
});
};
// calling our submit function.
$scope.regForm = function() {
// Posting data to file
$http.post('/tokken/s/', $scope.user).then(function (response) {
//$httpProvider.defaults.headers.common["X-AUTH-TOKEN"] = response.data;
if (response.errors) {
// Showing errors.
$scope.errorName = response.errors.name;
$scope.erroPassword = response.errors.password;
} else {
$scope.message = response.data;
}
});
};
});
/////////////
My html files is
<!DOCTYPE html>
<html ng-app="loginApp">
<head>
</head>
<body ng-controller="loginCtrl" ui-view="content">
<form ng-submit="submitForm()">
<br> user name:
<input type="text" ng-model="user.name">
<br>
<br> password:
<input type="text" ng-model="user.password">
<br>
<input type="submit" value="login">
</form>
</body>
<script src="/js/angular.min.js"></script>
<script src="/controller/login.js"></script>
<script src="/js/angular-ui-router.min.js"></script>
</html>
above code post a value. but didn't navigate to another page.
while i using $location provider in it. post didn't work. help me please
You should rather put the index contents into another template so that the state can return to "/" if the state changed, and because you set it as the default state: $urlRouterProvider.otherwise("/");
Add this to your stateProvider:
.state('login', {
url: '/',
templateUrl: 'templates/login.html',
controller: 'loginCtrl'
});
Also since your state is already assigning a controller the ng-controller="loginCtrl" in the body tag does not belong there.
Please check this code
.state('home', {
url: '/token/s',
views: {
'content#': {
templateUrl: 'templates/register.html',
controller: 'loginCtrl'
}
}
})
Instead of
.state('home', {
url: '/tokken/s/',
templateUrl: 'templates/register.html',
controller: 'loginCtrl'
});

change title of a page with angularjs routing

I want to change the page title of my page using routing, so far my title s getting changed but my url is being appended in the title. Any clue as to why?
index.html:
<title ng-bind-html="title ">Website Name</title>
JS file
app.config(function($stateProvider,$urlRouterProvider) {
.state('dashboard', {
url: "/dashboard",
templateUrl: "partials/content/dashboard.html",
controller: "dashboardCtrl"
})
});
app.run(function ($rootScope, $state, $stateParams) {
//set it here
$rootScope.title = $state.current.title;
});
Use $routeChangeSuccess .
app.run(['$location', '$rootScope', function($location, $rootScope) {
$rootScope.$on('$routeChangeSuccess', function (event, current, previous) {
$rootScope.title = current.$$route.title;
});
}]);
Then in Html , Use ng-bind
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title ng-bind="'myApp — ' + title">myApp</title>
Fore more reference read - How to dynamically change header based on AngularJS partial view? or How to set page title with Angular
Just put it into data:
app.config(function($stateProvider,$urlRouterProvider) {
.state('dashboard', {
url: "/dashboard",
templateUrl: "partials/content/dashboard.html",
controller: "dashboardCtrl",
data: {
title: 'Dashboard title'
}
}) });
You need to use the title property for the when function of $routeProvider, like so:
var module = angular.module('yourApp.routes', []);
module.config([
'$routeProvider', function ($routeProvider) {
$routeProvider
.when('/dashboard', {
title: 'Dashboard',
templateUrl: "partials/content/dashboard.html",
controller: "dashboardCtrl"
})
}
]);
return module;
Title can be accessed in $scope or in a view:
<h1 data-ng-bind="::title"></h1>

in $http. What is wrong with this code?

I made a function to do it. getTemplate it called
And I call it from templateUrl and I gives him the name of the state
I do not understand why it does not work for me,
Even it does not make me alert in errorCallback
And there are no errors in the console
<!DOCTYPE html>
<html>
<head>
<base href="{!! url() !!}/">
<title>{{ $title }}</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.2/angular-route.min.js"></script>
<script>
var BASE_URL = $('base').attr('href');
var menus = {!! $main_menu !!};
var app = angular.module('myApp', ['ui.router','ngRoute']);
app.directive('mainMenu', function(){
return {
restrict: 'E',
templateUrl: BASE_URL + 'assets/angularTemplates/main-menu.html',
controller: function($scope){
$scope.menus = window.menus;
$scope.BASE_URL = window.BASE_URL;
}
}
});
var getTemplate = function(name){
$http({
method: 'GET',
url: 'http://localhost/LaravelAngular/public/assets/angularTemplates/demo.html'
}).then(function successCallback(response) {
alert('yyyy');
}, function errorCallback(response) {
alert('nnnnn');
});
templates = {hfome : '<h1>Hi !! </h1>'};
if ( name in templates){
return templates[name];
}
alert(43)
};
var t = 'http://localhost/LaravelAngular/public/assets/angularTemplates/demo.html';
app.config(function($stateProvider, $urlRouterProvider, $locationProvider,$routeProvider) {
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
$stateProvider
.state('pages', {
url: '/:page',
template: function($stateParams){
return getTemplate($stateParams.page);
},
controller: function($stateParams){
alert($stateParams.page);
}
})
});
</script>
</head>
<body ng-app="myApp">
<div class="container">
<main-menu></main-menu><!-- Main menu created by angular -->
<a ui-sref="pages({ page: 'home' })">Home</a>
<div ui-view></div>
#yield('content')
</div><!-- end of container -->
</body>
</html>

could not modify view after calling ajax from controller using a factory

I have a demo app through which I want to display all countries data in a page(view) using angularjs.
Here is my code:
MyApp.js
var app = angular.module("MyApp", [ 'ui.bootstrap',
'ngRoute',
'MyControllers',
'MyFactory' ]);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/home', {
controller: 'MyController',
templateUrl: 'resources/modules/homeView/homeView.jsp'
})
.when('/view1', {
controller: 'MyController',
templateUrl: 'resources/modules/view1/view1.jsp'
})
.when('/view2', {
controller: 'MyController',
templateUrl: 'resources/modules/view2/view2.jsp'
})
.otherwise({redirectTo: '/home'});
}]);
MyControllers.js
var controllers = angular.module('MyControllers', []);
controllers.controller('MyController', ['$scope', 'Factory',
function($scope, Factory) {
$scope.countries = [];
$scope.showme = false;
$scope.CountryDetailsClick = function() {
var responsePromise = Factory
.getResponse("http://localhost:12345/DemoNew/getCountryList");
responsePromise.success(function(data, status, headers,
config) {
$scope.countries = data;
console.log("countryList size = " + $scope.countries.length);
$scope.showme = true;
});
responsePromise.error(function(data, status, headers,
config) {
alert("AJAX failed");
});
}
}]);
MyFactory.js
var myFactory = angular.module('MyFactory', []);
myFactory.factory('Factory', function($http) {
return {
getResponse : function(url) {
return $http.get(url);
}
}
});
View1.jsp
<body ng-view>
<h1 class="page-header">View1</h1>
{{countries.length}}
</body>
View2.jsp
<body ng-view>
<h1 class="page-header">View2</h1>
{{showme}}
</body>
homeView.jsp
<body ng-view>
<h1 class="page-header">Home</h1>
index.jsp
<body ng-app="MyApp" ng-controller="MyController">
<nav class="navbar navbar-default navbar-static-top" role="navigation"
style="margin-bottom: 0">
Country Details
Country Rate Plans
</nav>
<div id="page-wrapper" ng-view>
</div>
</body>
Now I am getting on console as :-
countryList size = 268
which is correct, I am using spring for backend. I am able to fetch data from the database.
But in View1 I get:
0
Also in View2 I get:
false
That means I am not able to reflect the fetched data to the view. Please help :(
===============================================================
After suggestions given by rob, i changed the following:
I changed my MyFactory.js to:
var myFactory = angular.module('MyFactory', []);
myFactory.factory('Factory', function($http) {
var current = {};
var factory = {
getResponse: function(urlReq){
var data = $http({method: 'GET', url: urlReq}).then(function (result){
current = result.data;
}, function (result){
alert("ERROR: No data returned");
});
},
getList: function(){
return current;
}
}
return factory;
});
And MyControllers.js to:
var controllers = angular.module('MyControllers', []);
controllers.controller('MyController',
function($scope, Factory) {
$scope.CountryDetailsClick = function() {
Factory.getResponse("http://localhost:12345/DemoNew/getCountryList");
}
});
controllers.controller('MyController3',
function($scope, Factory) {
console.log("in controller3");
});
controllers.controller('MyController2',
function($scope, Factory) {
console.log("in controller2");
$scope.countries = Factory.getList();
$scope.showme = true;
});
MyApp.js
app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/home', {
controller: 'MyController',
templateUrl: 'resources/modules/homeView/homeView.jsp'
})
.when('/view1', {
controller: 'MyController3',
templateUrl: 'resources/modules/view1/view1.jsp'
})
.when('/view2', {
controller: 'MyController2',
templateUrl: 'resources/modules/view2/view2.jsp'
})
.otherwise({redirectTo: '/home'});
}]);
View2.jsp
<body ng-view>
<h1 class="page-header">View2</h1>
{{showme}}
{{countries}}
</body>
When I click on Country Details, I get "true" and an empty array, but when I click Country Details after clicking Country Rate Plans, it works perfectly fine.
Please find the flaw.!!
You are using the same controller from index.jsp and from your views. So Angular is creating two instances of your controller each with it's own scope. You are calling CountryDetailsClick() from the ng-controller in index.jsp's scope but you are trying to show the value of countries.length from the view's scope.
If you want to share some functionality or state between different controllers (e.g. your CountryDetailsClick() function) then put it in a service.

Resources