This is my Angular controller:
var app = angular.module('app', []);
app.controller("ctrl", ['$scope', '$http', function ($scope, $http) {
var promise = $http.get("url1")
.then(function (response) {
console.log(response);
$scope.files = [response.data]
return $http.get('url2', {
params: {
id: response.data[0].Id
}
})
})
.then(function (response2) {
console.log(response2);
$scope.files = response2.data;
return response2.data;
})
}])
my HTML
<div ng-app="app" ng-controller="ctrl">
<script type="text/ng-template" id="category">
<strong>{{file.Name}}</strong>
<ul ng-if="(files | filter:{ParentId : file.Id}).length > 0">
<li ng-repeat="file in files | filter: {ParentId : file.Id" ng-include="'category'"></li>
</ul>
</script>
<ul class="btn-highlight plus">
<li ng-repeat="file in files | filter: {ParentId : 0}" ng-include="'category'"></li>
</ul>
</div>
ParentId = response.data.Id in my Angular controller.
My question is how can I include response and response2 in my scope called $scope.files at the same time and call my response.data.Id in my html code(ParentId)?
You should change your code to this.
var app = angular.module('app', []);
app.controller("ctrl", ['$scope', '$http', function ($scope, $http) {
var promise = $http.get("url1")
.then(function (response) {
var response1 = [];
console.log(response);
response1 = response.data;
$scope.files = [response.data]
return $http.get('url2', {
params: {
id: response.data[0].Id
}
})
})
.then(function (response2) {
console.log(response2);
var response2 = [];
response2 = response2.data;
var allResponse = [];
allResponse = response2.data.concat(response1);
$scope.files = allResponse;
return response2.data;
})}])
Try setting the scope outside of the promise .. but anyway why in god's name are you using nested promises instead of the $q service ? That's callbacksHell , and it sucks as code ..
Use the $q , that's its basic use case ..
var app = angular.module('app', []);
app.controller("ctrl", ['$scope', '$http', function ($scope, $http) {
$scope.files = [];
var promise = $http.get("url1")
.then(function (response) {
console.log(response);
return $http.get('url2', {
params: {
id: response.data[0].Id
}
})
})
.then(function (response2) {
console.log(response2);
$scope.files = response2.data;
return response2.data;
})
}])
Related
So far this is the complete source
angular
.module('app')
.factory('Friends', ['$http',function($http){
return {
get: function(){
return $http.get('api/friends.json')
.then(function(response){
alert(JSON.stringify( response.data));
return response.data;
});
}
};
}])
Controller:
angular.module("app")
.controller('homeCtrl',['$scope','Friends',
function($scope, Friends){
$scope.title = "Welcome";
$scope.items=["2016","2015", "2014"];
$scope.friends = Friends.get();
$scope.save = function(){
$http.post('/api/friends', friends);
}
}])
$stateProvider
.state('home',{
url:'/',
templateUrl:'templates/home.html',
controller: 'homeCtrl',
resolve : {
friends:['Friends', function(Friends){
return Friends.get();
}]
}
})
The result when I try to alert it:
The UI Blank:
*and my nav bar ddl is not working how to do the trick?
Friends.get() return a promise. You must use the then method :
Friends.get().then(function(data) { $scope.friends = data; }); //instead of $scope.friends = Friends.get();
you should use $q for promises:
angular
.module('app')
.factory('Friends', ['$http', '$q' ,function($http, $q){
var self = {};
self.get = function() {
var deferred = $q.defer();
$http.get('api/friends.json')
.success(deferred.resolve)
.error(deferred.reject)
return deferred.promise;
}
return self
}])
Resolve:
resolve : {
friends:['Friends', function(Friends){
return Friends.get();
}]
}
I am trying to achieve category sorting in Angular js but its not working properly. It pulls data from desciption as well. I want to restrict it to categories names but no luck.
JS code:
var myApp = angular.module('myApp', []);
myApp.factory('Items', ['$http', function($http){
return {
get: function(callback){
$http.get('items.json').success(function(data){
callback(data);
})
}
}
}]);
myApp.factory('Categories', ['$http', function($http){
return {
get: function(callback){
$http.get('categories.json').success(function(data){
callback(data);
})
}
}
}]);
// Config and Routes
myApp.config(function($routeProvider){
$routeProvider
.when('/', {
templateUrl:"home.html"
})
.when('/item/:id', {
templateUrl:"item.html"
})
})
myApp.controller('headerController', function($scope, $location) {
$scope.goHome = function () {
$location.path('/');
};
})
function Ctrl($scope) {
$scope.greeting = 'hello';
}
// Controllers
myApp.controller('ItemController', function($scope, $route, $location, $http, Items){
Items.get(function(response){
$scope.items = response;
});
// Update this value dynamically - onclick
$scope.filters = "food";
$scope.viewDetail = function(item) {
$location.path('/item/' + item.id);
}
})
myApp.controller('ListController', function($scope, $route, $location, $http, Categories){
$scope.sendCategory = function(category) {
// How can I pass this value to ItemController?
$scope.search =category.name;
};
$scope.orderProp='date';
$scope.tab = function (tabIndex) {
//Sort by date
if (tabIndex == 1){
//alert(tabIndex);
$scope.orderProp='date';
}
//Sort by views
if (tabIndex == 2){
$scope.orderProp = 'views';
}
};
$scope.sort = function(item) {
if ( $scope.orderProp == 'date') {
return new Date(item.date);
}
return item[$scope.orderProp];
}
})
myApp.controller('CategoryController', function($scope, $route, $location, $http, Categories){
Categories.get(function(response){
$scope.categories = response;
});
})
myApp.controller("tabsController", function ($scope) {
$scope.orderProp = 'date';
})
myApp.controller('ItemDetailController', function($scope, $route, $location, $http, Items){
Items.get(function(response){
$scope.items = response;
if ($route.current.params.id) {
angular.forEach($scope.items, function (v, k) {
if (v.id == $route.current.params.id) {
$scope.currItem = $scope.items[k];
return false;
}
});
}
});
})
can any one please help to find the way I can sort the data only as per my category names instead searching data on the overall pages?
Sharing the reference URL I found for this.
http://plnkr.co/edit/rh3wGYhuoHSHJEa4PoQi?p=preview
It would be great help if any can help me out.
I want to call a method from one controller to another controller. There are two controllers named "header" and "mainContent". Need to call a "trigger method" in the "header Controller", After the success call of "result method" in the mainController.
If that method called that should hide that paragraph.
<div ng-controller="header">
<p ng-show="msg">Content</p>
</div>
<div ng-controller="mainContent">
</div>
var module = angular.module("sourceViewer", ['ui.router']);
//header controller
module.controller('header', function ($scope, $location) {
$scope.msg=true;
$scope.trigger= function(data) { //This method should be called after the result method called in the mainContent Controller
$scope.$on('UPDATE_CHILD', function() {
if(data)
$scope.msg=false;
});
}
});
// mainContent controller
module.controller('mainContent', function ($scope, $location, dataService) {
$scope.user = dataService.user;
$scope.signIn = function (user) {
var result = dataService.login(user);
result.success(function (data) {
if (data.message== "success") {
$scope.$broadcast('UPDATE_CHILD');
//From here I want to call trigger method of header controller
}
})
};
});
did u try this?
module.controller('header', ['$scope', '$location', '$rootScope', function ($scope, $location, $rootScope) {
$scope.msg=true;
$scope.trigger= function(data) {
if(data)
$scope.msg=false;
};
$rootScope.$on('event:fire', $scope.trigger);
}]);
// mainContent controller
module.controller('mainContent', ['$scope', '$location', 'dataService', function ($scope, $location, dataService) {
$scope.user = dataService.user;
$scope.signIn = function (user) {
var result = dataService.login(user);
result.success(function (data) {
if (data.message== "success") {
$rootScope.$broadcast('event:fire');
}
})
};
}]);
You can use $rootScope like:
<div ng-controller="header">
<p ng-show="$root.header.msg">Content</p>
</div>
<div ng-controller="mainContent">
</div>
var module = angular.module("sourceViewer", ['ui.router']);
//header controller
module.controller('header', function ($rootScope,$scope, $location) {
$rootScope.header.msg = true;
});
// mainContent controller
module.controller('mainContent', function ($rootScope,$scope, $location, dataService) {
$scope.user = dataService.user;
$scope.signIn = function (user) {
var result = dataService.login(user);
result.success(function (data) {
if (data.message== "success") {
$rootScope.header.msg = true;
}
})
};
});
in the follwoing code you can see headerController is calling alert in mainController
myApp = angular.module("myApp",[]);
myApp.service("myService", function(){
showAlertBool = false;
return {
showAlert: function (value) {
showAlertBool = value;
},
canShowAlert: function () {
return showAlertBool;
}
}
});
myApp.controller("headerController", function($scope, myService){
console.log(myService);
$scope.clickHandler = function(){
myService.showAlert(true);
}
});
myApp.controller("mainController", function($scope, myService){
console.log(myService);
$scope.getServiceValue = function(){
return myService.canShowAlert();
}
$scope.$watch("getServiceValue()", function(newValue, oldValue){
if(newValue === true && newValue !== oldValue){
myService.showAlert(false);
alert("I can show Alert now!!!");
}
});
});
For a working code you can go here
I have created some search functionality with Angular js.
showing the HTML content using ngSanitize. Now in the HTML data I want to use jQuery onClick().
I tried a lot but no luck something is wrong:
Below is the Angular controls' code:
var myApp = angular.module('myApp', ['ngSanitize']);
myApp.factory('Items', ['$http', function($http){
return {
get: function(callback){
$http.get('assets/script/items.json').success(function(data){
callback(data);
})
}
}
}]);
myApp.factory('Categories', ['$http', function($http){
return {
get: function(callback){
$http.get('assets/script/categories.json').success(function(data){
callback(data);
})
}
}
}]);
// Config and Routes
myApp.config(function($routeProvider){
$routeProvider
.when('/', {
templateUrl:"home.html"
})
.when('/item/:id', {
templateUrl:"item.html"
})
})
myApp.controller('headerController', function($scope, $location) {
$scope.goHome = function () {
$location.path('/');
};
})
function controller($scope) {
$scope.greeting = 'hello';
}
// Controllers
myApp.controller('ItemController', function($scope, $route, $location, $http, Items){
Items.get(function(response){
$scope.items = response;
});
// Update this value dynamically - onclick
$scope.filters = "food";
$scope.viewDetail = function(item) {
$location.path('/item/' + item.id);
}
})
myApp.controller('ListController', function($scope, $route, $location, $http, Categories){
$scope.sendCategory = function(category) {
// How can I pass this value to ItemController?
$scope.search =category.name;
};
$scope.orderProp='title';
$scope.tab = function (tabIndex) {
//Sort by date
if (tabIndex == 1){
//alert(tabIndex);
$scope.orderProp='date';
}
//Sort by views
if (tabIndex == 2){
$scope.orderProp = 'views';
}
};
$scope.sort = function(item) {
if ( $scope.orderProp == 'date') {
return new Date(item.date);
}
return item[$scope.orderProp];
}
})
myApp.controller('CategoryController', function($scope, $route, $location, $http, Categories){
Categories.get(function(response){
$scope.categories = response;
});
})
myApp.controller("tabsController", function ($scope) {
$scope.orderProp = 'date';
})
myApp.controller('ItemDetailController', function($scope, $route, $location, $http, Items){
$scope.goHome = function () {
$location.path('/');
};
Items.get(function(response){
$scope.items = response;
if ($route.current.params.id) {
angular.forEach($scope.items, function (v, k) {
if (v.id == $route.current.params.id) {
$scope.currItem = $scope.items[k];
return false;
}
});
}
});
})
jSon Data sample:
[
{
"id": 1,
"title": "My Title",
"src": "assets/images/myPic.jpg",
"description": "<p>Hello p tag</p><h2>heading</h2><div>Content</div>",
"organization": "My Organization",
"currentrole": "My Current Role"
},
{
"id": 2,
"title": "My Title",
"src": "assets/images/myPic2.jpg",
"description": "<p>Hello p tag 2</p><h2>heading2</h2><div>Content 2</div>",
"organization": "My Organization",
"currentrole": "My Current Role"
}
]
Please help! Thanks in advance.
Why would you use jquery for a click event, You can use Angular ng-click event to bind any html element to an angular $scope function. Look at the docs:
Angular ngClick
You could also use standard javascript
var someelement = document.getElementById("myelement");
someelement .addEventListener("click",function(e){
//Insert code
},false);
here is the code what I meant:
myApp.controller('ItemDetailController', function($scope, $route, $location, $http, Items){
$scope.goHome = function () {
$location.path('/');
};
Items.get(function(response){
$scope.items = response;
if ($route.current.params.id) {
angular.forEach($scope.items, function (v, k) {
if (v.id == $route.current.params.id) {
$scope.currItem = $scope.items[k];
return false;
}
});
}
});
$('.detailed').on('click', 'h4', function(){
$(this).next('ul').slideToggle();
$(this).toggleClass('activeHead');
});
})
I have an angular controller called SubmissionTreeController and it has update_dashboard() function which refreshes the ui every minute.
My goal is to refresh the ui on successful post request from a different controller.
How do I make this function available in other controllers?
var module = angular.module("submissionDashboard", ['ui.tree', 'ngCookies', 'ui.bootstrap',]);
module.controller("SubmissionTreeController", ["$scope", "$http", "$modal",
function($scope, $http, $modal) {
$scope.selected_items = {};
var update_dashboard = function() {
var url = Django.url('submission:active_list_ajax', {
site : site
});
$http.get(url).success(function(data) {
$scope.list = data.results;
});
};
update_dashboard();
$scope.closeTask = function(scope) {
var modalInstance = $modal.open({
templateUrl: 'modal_close_submission_renderer.html',
controller: 'ModalCloseSubmissionController',
resolve: {
items: function () {
return $scope.selected_items;
}}
});
};
}]);
module.controller('ModalCloseSubmissionController', ['$scope', '$modalInstance', '$http', 'items', function ($scope, $modalInstance, $http, items) {
$scope.items = items;
$scope.selected = {
item: 1,
text: ''
};
$scope.ok = function () {
var val = $scope.selected.item;
if (val === 1) {
var url = Django.url('submission:close-notify', {
site : site
});
$http.post(url, $scope.selected_items).success(function(data) {
update_dashboard();
});
} else if (val === 2) {
var url = Django.url('submission:close', {
site : site
});
$http.post(url, $scope.selected_items).success(function(data) {
update_dashboard();
});
} else if (val === 3) {
var url = Django.url('submission:cancel', {
site : site
});
$http.post(url, $scope.selected_items).success(function(data) {
update_dashboard();
});
};
$modalInstance.close($scope.selected.item);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}]);
Edit:
What I am trying to do:
module.service('updateDashboardService', function($scope, $http){
this.update_dashboard = function() {
$scope = $scope;
var url = Django.url('submission:active_list_ajax', {
site : site
});
$http.get(url).success(function(data) {
$scope.list = data.results;
});
};
});
module.controller("SubmissionTreeController", ["$scope", "$http", "$modal", "updateDashboardService", function($scope, $http, $modal, updateDashboardService) {
$scope.selected_items = {};
updateDashboardService.update_dashboard();
var timer = setInterval(function() {
$scope.$apply(updateDashboardService.update_dashboard($scope, $http));
}, 1000 * 60);
What I am getting:
Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <- updateDashboardService
Edit 2:
module.service('updateDashboardService', function($rootScope, $http){
this.update_dashboard = function() {
var url = Django.url('submission:active_list_ajax', {
site : site
});
$http.get(url).success(function(data) {
$rootScope.list = data.results;
});
};
});
As #Gopesh says create a factory method, or, you can do something like this in SubmissionTreeController:
$scope.$on("event:updateDashboard", function(){ update_dashboard() });
And in your other controller:
$http.post(url, $scope.selected_items).success(function(data) {
$scope.$emit("event:updateDashboard");
});