I am using angular.js. I have a controller for my navbar which looks as follows.
var controllers = angular.module('controllers', []);
controllers.controller('NavbarController', ['$scope', '$http',
function ($scope, $http) {
$http.get('/api/courses')
.success(function(data) {
$scope.courses = data.objects;
});
}
]);
This will give me all the courses which have been created. I put it on the navbar like so:
<ul class="dropdown-menu">
<li ng-repeat="course in courses">
{{ course.name }}
</li>
</ul>
This works when I load my page. However, I have a form to create a NEW course, which also works. However, after this has been successfully submitted, the navbar will not contain the class until I completely reload the page. This is my controller which creates a new course.
controllers.controller('CreateCourseController', ['$scope', '$http',
function($scope, $http) {
$scope.form_data = {};
$scope.submitForm = function() {
$http.post('/api/courses', $scope.form_data).
success(function(data) {
// here, I want to add this item into the navbar selection somehow
});
}
}
]);
what would be the best way in angular to add this newly added class into the navbar, cleanly?
You could use $broadcast to send a message that the nav needs to be updated and use $on to listen for the event.
See: https://docs.angularjs.org/api/ng/type/$rootScope.Scope
Maybe something like this:
var controllers = angular.module('controllers', []);
controllers.controller('NavbarController', ['$scope', '$http',
function ($scope, $http) {
var updateNav = function() {
$http.get('/api/courses')
.success(function(data) {
$scope.courses = data.objects;
});
};
// Init
updateNav();
// Subscribe
$scope.$on('nav:updated', updateNav() );
}]);
controllers.controller('CreateCourseController', ['$scope', '$http',
function($scope, $http) {
$scope.form_data = {};
$scope.submitForm = function() {
$http.post('/api/courses', $scope.form_data).
success(function(data) {
// here, I want to add this item into the navbar selection somehow
$scope.$broadcast('nav:updated');
});
}
}]);
Related
I have used a controller in order to use an api which works fine but I want to use it using factory or service and have tried this so many times but may be I don't have that much understanding of it. I am currently taking a course for AngularJs, so I am sorry if I am asking something stupid.
Also it would be great anyone can tell me that what would be best to use factory or service or something else.
This way it works fine:
HTML:
<div ng-controller="PromiseCtrl">
<li ng-repeat="post in posts" >
{{post.link}}<br/>
{{post.title}}
</li>
</div>
Controller:
.controller('PromiseCtrl', ['$scope', '$http', function($scope, $http) {
$http.get('http://www.zemtv.com/wp-json/wp/v2/posts').then(function(value) {
$scope.posts = value.data;
});
}]);
This is where I am facing problem:
HTML:
<div ng-controller="PromiseCtrl">
<li ng-repeat="post in posts" >
{{post.link}}<br/>
{{post.title}}
</li>
</div>
Controller:
.controller('PromiseCtrl', ['$scope', '$http', function($scope, $http) {
$http.get('http://www.zemtv.com/wp-json/wp/v2/posts').then(function(value) {
$scope.posts = value.data;
});
}])
Factory:(I am not using this correctly, I think)
angular.module('confusionApp')
.factory('menuFactory', function() {
$http.get('http://www.zemtv.com/wp-json/wp/v2/posts').then(function(value) {
var posts = value.data;
});
});
I haven't tested any of this but it's along the lines of:
angular.module('confusionApp')
.factory('menuFactory', function() {
return {
getPosts: function () {
return $http.get('http://www.zemtv.com/wp-json/wp/v2/posts')
}
}
});
Then from the controller:
.controller('PromiseCtrl', ['$scope', '$http', 'menuFactory', function($scope, $http, menuFactory) {
menuFactory.getPosts().then(function(response){
$scope.posts = response.data;
});
}]);
It would be good to read what up more on the uses of services and how they are injected and used by controllers.
Here is the thing. I am not able to pass data from angular modal back to the controller where i need it. the codes given below.
Controller side
'use strict'
var DataMod = angular.module('Data', ["angularGrid", 'ui.bootstrap.contextMenu', 'ui.bootstrap']);
DataMod.controller('DataController', ['$scope', '$compile', '$uibModal', '$log','$rootScope', '$http', function ($scope, $compile, $uibModal,$log, $rootScope, $http, ngUtilityService) {
//user first clicks on Add button. A modal opens up. ModalInstanceCtrl is the controller used.
$scope.adduser = function () {
var modalInstance = $uibModal.open({
templateUrl: 'myModalContent.html',
controller: ModalInstanceCtrl
});
//response data should be available here.
};
var ModalInstanceCtrl = function ($scope, $uibModalInstance) {
//ajax call is made is inside this controller and i get a response.
//this response is an object. i need to pass this object back to the adduser function. mentioned it above.
};
}
]);
As you can see above, there is the main controller. I have used a modal inside there which has its own controller. I make ajax call inside that modals controller and get a response back.
I want that response as a result to be available back at the adduser function so that i can work with that data. However, it seems that once the adduser function starts, it goes to the ModalInstanceCtrl and ends its execution there. It doesnt come back to the adduser function at all. I need a way to get back to the adduser function.
Can anyone let me know how to achieve this. Also how to pass the object response from ModalInstanceCtrl to the main controller inside adduser function.
It looks like you are using the Angular Bootstrap Modal, yes? First, I would set it up so that the modal controller is separated out from the main controller. Second, you are missing the promise needed to pass the response from the modal to the main controller. You can read about the return modal instance in the docs here: https://angular-ui.github.io/bootstrap/#/modal
This is the example code from the Angular Bootstrap plunkr: http://plnkr.co/edit/nGjBtMp33pFDAQ6r7Tew?p=info
angular.module('ui.bootstrap.demo', ['ngAnimate', 'ui.bootstrap']);
angular.module('ui.bootstrap.demo').controller('ModalDemoCtrl', function ($scope, $uibModal, $log) {
$scope.items = ['item1', 'item2', 'item3'];
$scope.animationsEnabled = true;
$scope.open = function (size) {
var modalInstance = $uibModal.open({
animation: $scope.animationsEnabled,
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
size: size,
resolve: {
items: function () {
return $scope.items;
}
}
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
$scope.toggleAnimation = function () {
$scope.animationsEnabled = !$scope.animationsEnabled;
};
});
// Please note that $uibModalInstance represents a modal window (instance) dependency.
// It is not the same as the $uibModal service used above.
angular.module('ui.bootstrap.demo').controller('ModalInstanceCtrl', function ($scope, $uibModalInstance, items) {
$scope.items = items;
$scope.selected = {
item: $scope.items[0]
};
$scope.ok = function () {
$uibModalInstance.close($scope.selected.item);
};
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
});
I couldn't pass the parameter from angular controller to factory. Can any one help me on this? It works without passing parameter but when I pass it it's not.
var app = angular.module('employee', ['ui.grid', 'ui.grid.saveState', 'ui.grid.selection', 'ui.grid.cellNav', 'ui.grid.resizeColumns', 'ui.grid.moveColumns', 'ui.grid.pinning', 'ui.bootstrap', 'ui.grid.autoResize','ui.grid.pagination']);
app.controller('EmpCtrl', ['$scope', '$http', '$interval', '$modal', '$log', 'gridService', function ($scope, $http, $interval, $modal, $log, gridService) {
$scope.LoadNextPage = gridService.LoadNextPage("5");
}]);
var gridService = function ($http, $rootScope) {
return {
LoadNextPage: function (hh) {
alert(hh);
},
gridOptions:gridOptions
};
};
app.factory('gridService', ['$http', '$rootScope', gridService]);
And this is how I use it in the view
<span id="pcNext"
class="glyphicon glyphicon-step-forward"
ng-click="LoadNextPage()">
</span>
The problem is in your controller:
$scope.LoadNextPage = gridService.LoadNextPage("5");
This means that your LoadNextPage is not a function but rather a result of the call to a function in your service. Which btw doesn't return anything but rather just displays an alert. But in your view, you're using LoadNextPage as a function call...
Change it to this so your controller's LoadNextPage will be a function that you can call from the view.
$scope.LoadNextPage = gridService.LoadNextPage;
and in your view:
<span id="pcNext"
class="glyphicon glyphicon-step-forward"
ng-click="LoadNextPage(5)">
</span>
This should work.
Note: I suspect that your gridOptions are defined somewhere outside of scope of your code that you provided in the question so that it doesn't throw and error because of the missing (likely) object. So I considered this a typo in your code and not the actual problem.
Don't want params in your view?
No problem. You can either create a wrapper function or bind it to specific parameters in your code:
// wrap
$scope.LoadNextPage = function() {
return gridService.LoadNextPage("5");
};
// bind
$scope.LoadNextPage = gridService.LoadNextPage.bind(this, 5);
Or bake the number in your service...
Issue here is gridOptions:gridOptions is not defined which throws error.
Remove ,gridOptions:gridOptions from factory.
Check snippet for working code and compare with your code.
var app = angular.module('employee', []);
app.controller('EmpCtrl', ['$scope', 'gridService', function ($scope, gridService) {
$scope.clickMe = function() {
$scope.LoadNextPage = gridService.LoadNextPage("5");
}
}]);
var gridService = function() {
return {
LoadNextPage: function (hh) {
alert(hh);
}
};
};
app.factory('gridService', ['$http', '$rootScope', gridService]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="employee" ng-controller="EmpCtrl">
<button ng-click="clickMe()">Button</button>
</div>
you not defined gridOptions function see this link:
angular.module("myApp", []).controller("myCon", function($scope, $interval, gridService){
$scope.LoadNextPage = gridService.LoadNextPage("5");
}).factory('gridService', ['$http', '$rootScope', gridService]);
function gridService($http, $rootScope){
return {
LoadNextPage: function (hh) {
alert(hh);
}
};
}
see this link
I already have seem other topics with this kind of issue, but no one could help me... So here is my issue:
I have a navbar with a button for search, this buttons makes and get request from a webservice and returns a json object which must be apply to fill an table list. The problem is, my button and my table are in separated controllers, and it does work like I expected.
var app = angular.module('clientRest', []).controller('lista', ['$scope', 'loadLista', function($scope, loadLista) {
$scope.contatos = loadLista.getContatos();
}]).controller('pesquisa', ['$scope', '$http', 'loadLista', function($scope, $http, loadLista) {
$scope.listar = function() {
$http.get("http://localhost/wsRest/index.php/contato").success(function(response) {
loadLista.setContatos(response);
});
};
}]).service('loadLista', function() {
var contatos = [];
return {
getContatos: function() {
return contatos;
},
setContatos: function(c) {
contatos = c;
}
};
});
My code...
When I call listar() from pesquisa controller I need to send received data to $scope.contatos from lista controller to make my ng-repeat work, everything with a single click.
How can I do it?
Thanks everyone
Better to use a service to share data between two controllers / modules as this might be the best approach. You can refer the code segment given below to understand the concept.
angular.module('app.A', [])
.service('ServiceA', function() {
this.getValue = function() {
return this.myValue;
};
this.setValue = function(newValue) {
this.myValue = newValue;
}
});
angular.module('app.B', ['app.A'])
.service('ServiceB', function(ServiceA) {
this.getValue = function() {
return ServiceA.getValue();
};
this.setValue = function() {
ServiceA.setValue('New value');
}
});
In order to trigger the data receipt event, you may use
Broadcast / emit messages - with #broadcast / #emit
An angular promise with a call back
Controller initiation function to reload the previously read information from a service
.controller('MyController', function($scope, ServiceA) {
$scope.init = function() {
$scope.myValue = ServiceA.getValue();
};
// Call the function to initialize during Controller instantiation
$scope.init();
});
Use $rootScope.$emit to emit a change event when setting the variable and use $on to get the value in the lista controller. I used customListAr here just to demostrate a button click. Does this help?
var app = angular.module('clientRest', [])
.controller('lista', ['$scope', 'loadLista', '$rootScope',
function($scope, loadLista, $rootScope) {
console.log(loadLista);
$scope.contatos = loadLista.getContatos();
$rootScope.$on('change', function() {
$scope.contatos = loadLista.getContatos();
});
}
])
.controller('pesquisa', ['$scope', '$http', 'loadLista',
function($scope, $http, loadLista) {
$scope.listar = function() {
$http.get("http://localhost/wsRest/index.php/contato").success(function(response) {
loadLista.setContatos(response);
});
};
$scope.customListAr = function() {
loadLista.setContatos(["item 1" , "item 2", "item 3"]);
}
}
])
.service('loadLista', ['$rootScope',
function($rootScope) {
var contatos = [];
return {
getContatos: function() {
return contatos;
},
setContatos: function(c) {
contatos = c;
$rootScope.$emit('change');
}
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="clientRest">
<div ng-controller="lista">
<ul>
<li ng-repeat="a in contatos">{{a}}</li>
</ul>
</div>
<div ng-controller="pesquisa">
<button ng-click="customListAr()">Click Me</button>
</div>
</div>
Your problem is that when you do $scope.contatos = loadLista.getContatos(); you are setting a static value, and angular is unable to effectively create a watcher for that object because your setContatos method is creating a new object each time. To get around this, have the controller's scope hold a reference to the parent object and then it will automatically have a watcher on that object.
var app = angular.module('clientRest', [])
.controller('lista', ['$scope', 'loadLista', function($scope, loadLista) {
$scope.contatos = loadLista.contatos;
}])
.controller('pesquisa', ['$scope', '$http', 'loadLista', function($scope, $http, loadLista) {
$scope.listar = function() {
$http.get("http://localhost/wsRest/index.php/contato"
).success(function (response) {
loadLista.contatos.data = response;
});
};
}])
.service('loadLista', function() {
var lista = {
contatos: {},
};
return lista;
});
// view:
<ul>
<li ng-repeat="contato in contatos.data">
{{ contato }}
</li>
</ul>
I have an app that uses dynamic routing to load modal windows, with each window displaying one "activity" object from a JSON file. Currently I'm using the route to determine which card is visible, and then calling a data service to fill in the data based on a match with the route name.
But I don't like this solution, as it isolates my current card from the context of the array. I would far prefer to be able to pass the card object from the template, because then I will know what the $index is, which I can then use to navigate to "prev" and "next" elements.
If I have this mark-up:
<div ng-controller="MenuCtrl">
<ul class="menu">
<li ng-repeat="card in cards">
{{ card.shortName }}
</li>
</ul>
</div>
Which triggers this $routeProvider:
$routeProvider
.when('/page/:name', {
templateUrl : 'modalContainer',
controller : 'ModalContainerCtrl'
})
Which brings up this controller:
.controller('ModalContainerCtrl',['$scope', '$modal', '$route', function($scope, $modal, $route) {
var modalInstance = $modal.open({
templateUrl : '../assets/templates/modal.html',
controller: 'ModalCtrl'
});
$scope.activity = $route.current.pathParams.name;
console.log($scope.activity);
//Modal controls
$scope.close = function () {
console.log("close!");
$modalInstance.close();
};
}])
is there any way I can pass the card object to ModalContainerCtrl via this routing or any other means?
You can pass a scope object to a modal window controller using the resolve (definition of resolve Members that will be resolved and passed to the controller as locals; it is equivalent of the resolve property for AngularJS route). So in your case it can be done like this:
.controller('ModalContainerCtrl',['$scope', '$modal', '$route', function($scope, $modal, $route) {
//your card object
$scope.card = '';
var modalInstance = $modal.open({
templateUrl : '../assets/templates/modal.html',
controller: 'ModalCtrl',
resolve: {
card: function () {
return $scope.card;
}
}
});
$scope.activity = $route.current.pathParams.name;
console.log($scope.activity);
//Modal controls
$scope.close = function () {
console.log("close!");
$modalInstance.close();
};
}])
and in the modal controller:
var ModalCtrl = function ($scope, $modalInstance,card) {
//Modal controls
//card now can be used over here
$scope.close = function () {
console.log("close!") //This will now run
modalInstance.close();
};
}