Ui-Router Create New Controller In View - angularjs

Given that I am going to the following state:
$stateProvider.state('applicant', {
url: "/admin/applicants/:name",
templateProvider: function($http, $stateParams) {
return $http({
method: 'GET',
url: 'http://example.com/applicant',
params: {
request: $stateParams.name,
}
}).then(function successCallback(html) {
return html.data;
});
},
controller: 'SendToCtrl'
});
With the view that is being returned by $http looking like this:
<script>
app.controller('ChildController', ['$scope', function($scope) {
$scope.applicant = <?php echo $applicant ?>;
}]);
</script>
<div class="row" ng-controller="ChildController">
<div class="col-md-12">
{{applicant.State}}
</div>
</div>
I get a Argument 'ChildController' is not a function error. I read that in the regular ng-view calling a new controller like this is not supported, but couldn't find an answer for ui-router. What would be the proper way to do templating then if I need the template to display data that is only there once the view is served?

So I couldn't generate the controller from within the view like I wanted, so instead I used the controller generated by the state and attached the php variable to the view, then picked it back up again from said set controller, like so:
State Definition:
$stateProvider.state('applicant', {
url: "/admin/applicants/:name",
templateProvider: function($http, $stateParams) {
return $http({
method: 'GET',
url: 'http://example.com/applicant',
params: {
request: $stateParams.name,
}
}).then(function successCallback(html) {
return html.data;
});
},
controller: 'SendToCtrl'
});
View:
<?php
$applicant = str_replace('"', "'", $applicant);
?>
<div class="row">
<div id="fetchMe" class="col-md-12">
</div>
</div>
<script>
applicant = <?php echo $applicant ?>;
$('#fetchMe').data('key',applicant);
</script>
SendToCtrl:
app.controller('SendToCtrl', ["$scope", "$stateParams", "$state", function($scope, $stateParams, $state) {
console.log($stateParams);
$scope.applicant = $("#fetchMe").data('key');
console.log($scope.applicant);
}]);
:)

Related

status undefined when try to fetch data on json and place it on single page of each data

heres my code, i try to show my selected product form my product page by id.
for example when i click a product it go to right url like /#/product/2 and it show all the attribute of product id:2. please take a look this code
app.js
angular
.module('app', [
'ui.router',
'app.directives.productCard'
])
.config(['$urlRouterProvider', '$stateProvider', function($urlRouterProvider, $stateProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateUrl: 'templates/pages/home.html',
controller: 'homeCtrl'
})
.state('product', {
url: '/product',
templateUrl: 'templates/pages/product.html',
controller: 'productCtrl'
})
.state('productDetails', {
url: '/product/:id',
templateUrl: 'templates/pages/productDetails.html',
controller: 'productDetailsCtrl'
})
}])
my services
angular
.module('app')
.factory('Product', ['$http', function($http) {
return {
get: function() {
return $http.get('https://raw.githubusercontent.com/vicariosinaga/learn/master/products.json').then(function(response) {
return response.data;
});
}
};
}])
productCtrl
angular
.module('app')
.controller('productCtrl',['$scope', 'Product', function($scope,Product) {
$scope.title="List Product";
Product.get().then(function(data) {
$scope.products = data;
});
$scope.products=Product.get();
}]);
productdetailsCtrl
angular
.module('app')
.controller('productDetailsCtrl',['$scope','$stateParams', 'Product', function($scope,$stateParams,Product){
$scope.id=$stateParams.id;
Product.get().then(function(data) {
var singleProduct = data.filter(function(entry){
return entry.id === $scope.id;
})[0];
console.log(singleProduct);
console.log($stateParams);
});
}]);
product.html
<div class="col-lg-3 col-md-4 col-sm-6">
<div class="card">
<img class="card-img-top" ng-src="{{item.image}}" alt="{{item.name}}">
<div class="card-block">
<strong class="card-title">{{item.name}}</strong>
</div>
<div class="card-block">
Buy
</div>
</div>
</div>
product detail.html
<p>{{id}}</p>
<p>{{name}}</p>
<p>{{image}}</p>
after all this code,when i try to check via console. i get Object {id: "2"}, but when i try to show all the attribute from product 2 i get on console undefined. why i got undifined. yeah i didnt use and local server. but if its the problem. does all the code is right to print all the attribut of product 2
here the link of the json https://raw.githubusercontent.com/vicariosinaga/learn/master/products.json
Change product details state url to make id parameter as a int which will allow you to pass return entry.id === $scope.id;(strict equality check).Here you have id value as string which makes singleProduct as undefined.
.state('productDetails', {
url: '/product/{id:int}',
templateUrl: 'templates/pages/productDetails.html',
controller: 'productDetailsCtrl'
})
otherwise you have to change your strict check to return entry.id == $scope.id;

Angular UI Router - Load View With Controller Embedded

Instead of doing two $http requests, one for the controller data and one for the view data, how come I can't just load a view and have a controller embedded in the view? It doesn't work.
My router code:
app.config(function($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise("/admin");
$stateProvider.state('home', {
url: "",
templateProvider: function($http, $stateParams) {
return $http({
method: 'GET',
url: '/admin/home'
}).then(function successCallback(html) {
return html.data;
});
},
controller: function($scope) {
// $scope.activeSection.activeSection = "notNone";
}
})
//all other states go here
});
My view returned from the templateProvider $http promise:
<div class="container" ng-controller="home">
{{orders[0]}}
</div>
<script>
app.controller('home', ['$scope', '$http', '$state', function($scope, $http, $state) {
$scope.orders = <?php echo json_encode($data[0]); ?>;
}]);
</script>
But I get an error saying "home" is undefined. I understand I can just set the controller on the route and do a $http request from there but it seems silly if I can just get what I need from a controller standpoint already in the view. Right? Or am I missing something. It would make it easier on the server to not have multiple routes (view and controller) for what is essentially one route.

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

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.

UI-Router don't route with param

I use UI-Router. I have a first controller
vehicuels.controller.js:
'use strict';
angular.module('autoPrivilegeApp')
.controller('VehiculesCtrl', function ($scope,$http, $state) {
$scope.awesomeThings = [];
$http.get('/api/cars').success(function (awesomeThings) {
$scope.message = awesomeThings;
});
// Show Car detail
$scope.showCarDetail = function (_id) {
$state.go('vehiculeDetail', {id: _id});
};
});
vehicules.js:
'use strict';
angular.module('autoPrivilegeApp')
.config(function ($stateProvider) {
$stateProvider
.state('vehicules', {
url: '/vehicules',
templateUrl: 'app/vehicules/vehicules.html',
controller: 'VehiculesCtrl'
});
});
vehicules.html:
<div class="col-md-12">
<div ng-repeat="car in message">
<button class="medium bouton bleu" ng-click="showCarDetail(car._id);">
{{ car._id }}
</button>
<br/><br/><br/><br/>
</div>
</div>
I want to pass id to my second controller
vehiculeDetail.controller.js:
'use strict';
angular.module('autoPrivilegeApp')
.controller('VehiculeDetailCtrl', function ($scope,$stateParams ) {
$scope.message = $stateParams.instanceID;
});
vehiculeDetails.js:
'use strict';
angular.module('autoPrivilegeApp')
.config(function ($stateProvider) {
$stateProvider
.state('vehiculeDetail', {
url: '/vehiculeDetail/{id}',
templateUrl: 'app/vehiculeDetail/vehiculeDetail.html',
controller: 'VehiculeDetailCtrl'
});
});
vehiculeDetail.html:
<div class="col-md-12">
This is the vehiculeDetail id {{message}}.
</div>
I have use the yeoman generator --> generator-angular-fullstack
my problem is that I do not get my id in my controller VehiculeDetailCtrl.
What is wrong?
The $stateParams uses name as they are defined in url:
$stateProvider
.state('vehiculeDetail', {
url: '/vehiculeDetail/{id}', // here we name our param as 'id'
So, we have to use now the name id instead of the instanceID
.controller('VehiculeDetailCtrl', function ($scope,$stateParams ) {
//$scope.message = $stateParams.instanceID;
$scope.message = $stateParams.id;

Resources