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");
});
Related
I am having problem while injecting dependency from service to controller. Although i added it but still same error of
Unknown provider: websiteFactoryProvider <- websiteFactory <- listCtrl
I basically need to render a ng-view to my index.html
Index.html
<div ng-view>
</div>
app.js
var app = angular.module('app', ['ngRoute']);
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/list', {
templateUrl: 'app/views/list.html', controller: 'listCtrl'
}).
otherwise({
redirectTo: '/list'
});
}]);
websiteService.js
app.factory('webiteFactory', ['$http', '$location', function ($http, $location) {
var factory = {};
// method that return all websites from an http request
factory.getAllWebsites = function () {
return $http.get("http://localhost/Replicate/GetAllWebsites");
}
//method that returns an object from given array
factory.getFilteredObject = function (list, websiteName) {
for (i = 0 ; i < list.length ; i++) {
if (list[i].Name == websiteName)
return list[i];
}
}
return factory;
}]);
/* application services that would not return values */
app.service('websiteService', ['$http', function ($http) {
//service for pagination
this.paginate = function ($scope) {
//pagination code
$scope.currentPage = 1;
$scope.totalItems = $scope.model.length;
$scope.numPerPage = 10;
$scope.paginate = function (value) {
var begin, end, index;
begin = ($scope.currentPage - 1) * $scope.numPerPage;
end = begin + $scope.numPerPage;
index = $scope.model.indexOf(value);
return (begin <= index && index < end);
};
//ordering code
$scope.reverse = true;
$scope.order = function (predicate) {
$scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
$scope.predicate = predicate;
};
}
//service to change state of a website
this.changeSiteState = function (website) {
var newState = website.State == "Stopped" ? "Started" : "Stopped";
$http({
method: 'POST',
url: '/Replicate/ChangeState/',
data: JSON.stringify({ webName: website.Name, state: newState }),
headers: { 'Content-Type': 'application/json' }
}).success(function (data) {
if (data == "success") {
website.State = website.State == "Stopped" ? "Started" : "Stopped";
}
else {
alert(data);
}
}).error(function (data, status, headers, config) {
alert(data);
});
}
}])
listCtrl.js
app.controller('listCtrl', function websiteCtrl($scope, $location, websiteFactory, websiteService, $modal) {
//function triggered at the intialization of controller
$scope.init = function () {
$scope.model = [];
setTimeout(function () {
websiteFactory.getAllWebsites().success(function (data) {
$scope.model = data;
websiteService.paginate($scope);
})
}, 0);
};
//delegation of change state to service method
$scope.changeState = function (website) {
websiteService.changeSiteState(website);
}
//open modal and shows details of single object
$scope.showDetails = function (websiteName) {
var modalInstance = $modal.open({
templateUrl: '../Views/Replicate/Details.html',
controller: 'DetailsCtrl',
resolve: {
obj: function () {
return websiteFactory.getFilteredObject($scope.model, websiteName);
}
}
});
}
});
You have misspelled "websiteFactory". In your factory definition code it is "webiteFactory" but in controller you are fetching it with different name using "websiteFactory" that's why it is not able to find this provider and producing error:
change:
app.factory('websiteFactory', ['$http', '$location', function ($http, $location) {
var factory = {};
// method that return all websites from an http request
factory.getAllWebsites = function () {
return $http.get("http://localhost/Replicate/GetAllWebsites");
}
//method that returns an object from given array
factory.getFilteredObject = function (list, websiteName) {
for (i = 0 ; i < list.length ; i++) {
if (list[i].Name == websiteName)
return list[i];
}
}
return factory;
}]);
That error comes when your factory is not registered with angular . Change it to
app.factory('websiteFactory', ['$http', '$location', function ($http, $location) {
...do something here...
}
How do I include ui.bootstrap. I use ui.bootstrap to open the bootstrap modal(open) on ng-click. After that I want to send all modal data to server, for that I use $http in my angular controller. But it gives an error. Below is my angular js code.
var app = angular.module("modalFormApp", ['ui.bootstrap']);
app.controller("modalAccountFormController", ['$scope', '$modal', '$log', '$http'
function($scope, $modal, $log, $http) {
$scope.showForm = function() {
$scope.message = "Show Form Button Clicked";
console.log($scope.message);
var modalInstance = $modal.open({
templateUrl: 'modal-form.html',
controller: ModalInstanceCtrl,
scope: $scope,
resolve: {
userForm: function() {
return $scope.userForm;
}
}
});
modalInstance.result.then(function(selectedItem) {
$scope.selected = selectedItem;
}, function() {
$log.info('Modal dismissed at: ' + new Date());
});
};
}
]);
app.controller('ModalInstanceCtrl', ['$scope', '$http', '$modalInstance', userForm, function($scope, $http, $modalInstance, userForm) {
//var ModalInstanceCtrl = function ($scope, $modalInstance,$http, userForm) {
$scope.form = {}
$scope.url = 'submit.php';
$scope.submitForm = function() {
if ($scope.form.userForm.$valid) {
$http.post($scope.url, {
"name": $scope.name,
"email":
$scope.email,
"message": $scope.message
}).
success(function(data, status) {
console.log(data);
$scope.status = status;
$scope.data = data;
$scope.result = data;
})
} else {
console.log('userform is not in scope');
}
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
}])
'ui.bootstrap' has prerequisites 'ngAnimate' and 'ngTouch'. You should add them to your module
var app = angular.module("modalFormApp", ['ngAnimate','ngTouch','ui.bootstrap']);
And you should add their scripts to your view
script(src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-animate.min.js")
script(src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-touch.min.js")
What specific changes need to be made to the AngularJS code below to check for the existence of a cookie named myCookie every time a page is loaded, and then to set the $rootScope.myCookieValue variable to become the value of myCookie?
The code is from the sample app whose complete code you can explore at this link. It is a very simple example app, and I just want a simple working solution to this so that I can build up more complex approaches from it.
angular.module('hello', [ 'ngRoute' ]).config(function($routeProvider, $httpProvider) {
$routeProvider.when('/', {
templateUrl : 'home.html',
controller : 'home',
controllerAs : 'controller'
}).otherwise('/');
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
$httpProvider.defaults.headers.common['Accept'] = 'application/json';
}).controller('navigation',
function($rootScope, $http, $location, $route) {
var self = this;
self.tab = function(route) {
return $route.current && route === $route.current.controller;
};
$http.get('user').then(function(response) {
if (response.data.name) {
$rootScope.authenticated = true;
} else {
$rootScope.authenticated = false;
}
}, function() {
$rootScope.authenticated = false;
});
self.credentials = {};
self.logout = function() {
$http.post('logout', {}).finally(function() {
$rootScope.authenticated = false;
$location.path("/");
});
}
}).controller('home', function($http) {
var self = this;
$http.get('resource/').then(function(response) {
self.greeting = response.data;
})
});
you can do it in run block I guess:
angular.module('hello', ['ngCookies', 'ngRoute'])
.config(function ($routeProvider, $httpProvider) {
$routeProvider.when('/', {
templateUrl: 'home.html',
controller: 'home',
controllerAs: 'controller'
}).otherwise('/');
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
$httpProvider.defaults.headers.common['Accept'] = 'application/json';
}).run(function ($rootScope, $cookies) {
var cookieValue = $cookies.get("myCookie");
if (cookieValue) {
$rootScope.myCookieVar = cookieValue;
}
}).controller('navigation',
function ($rootScope, $http, $location, $route) {
var self = this;
self.tab = function (route) {
return $route.current && route === $route.current.controller;
};
$http.get('user').then(function (response) {
if (response.data.name) {
$rootScope.authenticated = true;
} else {
$rootScope.authenticated = false;
}
}, function () {
$rootScope.authenticated = false;
});
self.credentials = {};
self.logout = function () {
$http.post('logout', {}).finally(function () {
$rootScope.authenticated = false;
$location.path("/");
});
}
}).controller('home', function ($http) {
var self = this;
$http.get('resource/').then(function (response) {
self.greeting = response.data;
})
});
I think you should use angular version > 1.4.x
you should also add reference angular-cookies.js
I know this is easy, but I can't quite wrap my head around how to do this.
I need to do the API call within a service so that those variables can be accessed between two separate controllers.
The problem I am having is I can't access $routeParams (which I need for the get) within the service. I can't figure out know how to pass $routeParams from the controller to the service.
app.controller('Main', ['$scope', 'Page', '$routeParams', '$http', function($scope, Page, $routeParams, $http) {
$scope.Page = Page;
}]);
app.controller('Pages', ['$scope', 'Page', '$routeParams', '$http', function($scope, Page, $routeParams, $http) {
$scope.Page = Page.posts;
}]);
app.factory('Page', ['$routeParams', '$http', function($routeParams, $http) {
var posts = function posts() {
$http.get('wp-json/wp/v2/pages/?filter[name]='+ $routeParams.slug).success(function(res){
console.log(JSON.stringify(res) );
});
};
var description = '';
var title = '';
return {
title: function () { return title; },
setTitle: function (newTitle) { title = newTitle; },
description: function () { return description; },
setDescription: function (newDescription) { description = newDescription; },
posts
};
}]);
factory :
app.factory('Page', ['$http', function($http) {
var _posts = function posts(param) {
return $http.get('wp-json/wp/v2/pages/?filter[name]='+ param);
};
var description = '';
var title = '';
return {
title: function () { return title; },
setTitle: function (newTitle) { title = newTitle; },
description: function () { return description; },
setDescription: function (newDescription) { description = newDescription; },
posts : _posts
};
}]);
Controller :
app.controller('Pages', ['$scope', 'Page', '$routeParams', '$http', function($scope, Page, $routeParams, $http) {
Page.posts($routeParams.slug).then(function success(response) {
$scope.Page = response.data;
}, function error(reason) {
// do something
});
}]);
please note that success is deprecated in newer versions of Angular. I have updated the code with then
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');
});
})