in $http. What is wrong with this code? - angularjs

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>

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'
});

Angular ui-router resolve http empty value

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;
});

Scope of all controllers not saving in the service in routing -Angularjs

I'm new to angular js. I was trying to save and share the scope of two different controllers.
Below is my script and views.
script.js:
var app = angular.module('app', ['ngRoute']);
app.run(function ($rootScope) {
$rootScope.$on('scope.stored', function (event, data) {
console.log("scope.stored", data);
});
});
app.controller('FirstController', function($scope) {
$scope.counter = 0;
$scope.add = function(amount) { $scope.counter += amount; };
$scope.subtract = function(amount) { $scope.counter -= amount; };
});
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/v1', {
templateUrl: 'views/v1.ejs',
controller: 'controller1'
}).
when('/v2', {
templateUrl: 'views/v2.ejs',
controller: 'controller2'
})
}]);
app.controller('controller1', function($scope,Scopes) {
Scopes.store('controller1',$scope);
$scope.data = "controller1";
$scope.buttonClick = function () {
console.log( Scopes.get('controller2').data);
};
});
app.controller('controller2', function($scope,Scopes) {
Scopes.store('controller2',$scope);
$scope.data = "controller2";
$scope.buttonClick = function () {
console.log( Scopes.get('controller1').data);
};
});
app.factory('Scopes', function ($rootScope) {
var mem = {};
return {
store: function (key, value) {
$rootScope.$emit('scope.stored', key);
mem[key] = value;
},
get: function (key) {
return mem[key];
}
};
});
index.html:
<!doctype html>
<html ng-app="app">
<head>
<script src="js/angular.min.js"></script>
<script src="js/angular-route.min.js"></script>
<script src="js/script.js"> </script>
</head>
<body>
<a href='#v1'>View1</a>
<a href='#v2'>View2</a>
<div ng-view>
</div>
</body>
</html>
v1.ejs:
<div ng-controller="controller1">
{{data}}
<br>
<button ng-click="buttonClick()">Clickme!</button>
</div>
v2.ejs:
<div ng-controller="controller2">
{{data}}
<br>
<button ng-click="buttonClick()">Clickme!</button>
</div>
The problem is:
Whenever the page is loaded, #/v1 is triggered.
If i click on 'Clickme', JUST AFTER THE PAGE LOADS, Error: Scopes.get(...) is undefined is fired.
But, if i navigate to #/v2 and then to #/v1, the scopes are getting stored and the error is NOT fired.
Is there is some problem with with routeProvider? All the controllers wont be loaded at on-load event?
Please help me on this.

AngularJS $routeProvider.when() 's resolve route parameter - what is that 'key'?

AngulaR resolve API
The API says for resolve:
key – {string}: a name of a dependency to be injected into the controller.
#egghead, there is this video on the topic:
egghead - Angular resolve
What i do not understand is what that key object is for and why the author of the above video does inject the controller into itself
key – {string}: a name of a dependency to be injected into the
controller.
app.config(function($routeProvider) {
$routeProvider.
when('/', {
controller: 'ListCtrl',
resolve: {
myResolve: function(MyService) {
return MyService();
}
},
templateUrl:'./views/list.html'
})
});
Instead of (in the controller)
app.controller('MyController',function($scope,MyService){
$scope.data = MyService();
});
if you use resolve
app.controller('MyController',function($scope,myResolve){
$scope.data = myResolve;
});
UPDATE
a working example
<!doctype html>
<html ng-app="myModule">
<head>
<meta charset="utf-8">
</head>
<body>
<div id="content" data-ng-view=""></div>
<script src="http://code.angularjs.org/1.0.8/angular.min.js"></script>
<script>
var myModule = angular.module('myModule', []);
myModule.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: './index.html',
controller: 'IndexCtrl',
resolve: {
hello: function(Hello) {
return Hello.getMessages();
}
}
})
.otherwise({
redirectTo: '/'
});
});
myModule.factory('Hello', function($q, $timeout) {
var getMessages = function() {
var deferred = $q.defer();
$timeout(function() {
deferred.resolve('Hello');
}, 1000);
return deferred.promise;
};
return {
getMessages: getMessages
};
});
myModule.controller('IndexCtrl',function($scope,hello){
$scope.hello = hello;
});
</script>
</body>
</html>
the view
<p>{{hello}}</p>

Resources