How to pass data to an angular-foundation modal $scope? - angularjs

I am using angular-foundation and specifically the modal http://madmimi.github.io/angular-foundation/#/modal , i am confused in how to pass data to a modal while using one controller , i want to take an array value and update the modal to show a particular user info ,Ex: $scope.updateUserInfo = $scope.user[index] , the only issue is how to pass the data to the modal .
myApp.controller('users',function ($scope,$location,$http,$modal,msg) {
$http.get('api/v1/users')
.success(function (data,status) {
$scope.user = data;
})
.error(function (data,status) {
$location.path('/login');
});
$scope.showWrite = function () {
$scope.write = true;
}
$scope.closeWrite = function () {
$scope.write = false;
$scope.newUser = '';
}
$scope.save = function () {
$http.post('api/v1/users/store',$scope.newUser)
.success(function (data,status) {
$scope.user.unshift({
id: data,
first_name: $scope.newUser.first_name,
last_name: $scope.newUser.last_name,
email: $scope.newUser.email,
role: $scope.newUser.role
});
$scope.write = false;
$scope.newUser = '';
})
.error(function (data,status) {
alert('failed');
});
}
$scope.confirmDelete = function (index,id) {
msg.confirmDelete().then(function(value) {
$scope.text = msg.getText();
$http.get('api/v1/users/destroy/'+id)
.success(function (data,status) {
$scope.user.splice(index,1);
})
.error(function (data,status) {
alert('Error : Operation failed');
});
});
}
$scope.showUserInfo = function () {
}
$scope.userUpdate = function () {
}
$scope.showUserUpdate = function (index) {
$modal.open({
templateUrl: 'partials/message/update.html',
controller: 'users'
});
}
});

To Pass the data to $modal you need to update your $modal function something like this:
$scope.showUserUpdate = function (popUpData) {
var modalInstance = $modal.open({
templateUrl: 'partials/message/update.html',
controller: ['$scope', '$rootScope', '$modalInstance',
function($scope, $rootScope, $modalInstance) {
$scope = angular.extend($scope, popUpData);
}],
resolve: {}
});
return modalInstance;
};
So popupData is the data which you want to pass to your modal. popupdata then will be merged with existing scope of that controller. Now you can access popupData keys in your HTML. Remember we are returning modal instance in this function so you can manually close the popup using this intance.

Other way is to use the resolve attribute and inject it to controller:
$scope.showUserUpdate = function (popUpData) {
var modalInstance = $modal.open({
templateUrl: 'partials/message/update.html',
controller: ['$modalInstance', 'data', function($modalInstance, data) {
data.popUpData = ...
}],
resolve: {
data: popUpData
}
});
return modalInstance;
};

Related

How to call MVC Web API Controller after AngularJS popup completes

I have an AngularJS module with code that calls a modal popup. I also have code that calls an MVC Web API controller method. Both of these functions work independently of one another right now. What I would like to happen is after the user clicks the OK button on the modal, I want to get the value of the modal text box and send it to the API controller as a parameter. The code I have so far is below:
app.js:
(function () {
'use strict';
var app = angular.module("CRNApp", ['ui.bootstrap','trNgGrid']);
var MainController = function ($scope, $http, $log, $uibModal) {
$scope.showGrid = false;
$scope.showPolicyScreen = false;
$scope.CRNViewModel = {
policyId: 0
};
$scope.openPolicyId = function () {
$uibModal.open({
templateUrl: 'templates/popupGetPolicy.cshtml',
backdrop: false,
windowClass: 'modal',
controller: function ($scope, $uibModalInstance, $log, CRNViewModel) {
$scope.CRNViewModel = CRNViewModel;
$scope.submit = function () {
}
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
},
resolve: { CRNViewModel: function () { return $scope.CRNViewModel; } }
});//end of modal.open
}; // end of scope.open fu
$scope.policyLookup = function (policyNumber) {
$scope.loading = true;
$scope.CRNViewModel.policyId = policyNumber; //"WCZ25999"
$http.post("/api/Policy"
, $scope.CRNViewModel
, { header: { 'Content-Type': 'application/json' } })
.then(function (response) {
$scope.policy = response.data;
$scope.loading = false;
$scope.showGrid = false;
$scope.showPolicyScreen = true;
})
.catch(function (error) {
console.log(error);
$scope.loading = false;
$scope.showGrid = false;
});
};
};
app.controller("MainController", MainController);
}());
The MVC API Controller method:
// POST: api/Policy
public IHttpActionResult Post([FromBody]CRNViewModel policy)
{
CRNViewModel _crnVM = new CRNViewModel();
IConditionalRenewalNotices _crn = new ConditionalRenewalNoticesRepository();
_crnVM = _crn.GetPolicyByPolicyId(policy.PolicyId);
return Json(_crnVM);
}
Return the textbox value when you close the $uibModalInstance instance and then add a callback for the modal result:
var modal = $uibModal.open({
templateUrl: 'templates/popupGetPolicy.cshtml',
backdrop: false,
windowClass: 'modal',
controller: function($scope, $uibModalInstance, $log, CRNViewModel) {
$scope.CRNViewModel = CRNViewModel;
$scope.submit = function () {
// pass in the value you want to return
$uibModalInstance.close('WCZ25999');
}
$scope.cancel = function() {
$uibModalInstance.dismiss('cancel');
};
},
resolve: { CRNViewModel: function() { return $scope.CRNViewModel; } }
});
modal.result.then(function (value) {
$scope.policyLookup(value);
});

adding several functions to one controller angular

Im trying to add another function to my controller but it keeps breaking the controller.
here is my code:
.controller('ClimbController', [
'$scope', '$stateParams', 'Climbs', function(
$scope, $stateParams, Climbs) {
var climb_id = $stateParams.climbId;
var areaId = $stateParams.areaId;
if (!isNaN(climb_id)) {
climb_id = parseInt(climb_id);
}
if (!isNaN(areaId)) {
areaId = parseInt(areaId);
}
$scope.selected_ = {};
$scope.items = [];
$scope.details = true;
// looping though all data and get particular product
$scope.selectClimb = function(areas){
areas.forEach(function(data) {
if(data._id == climb_id){
$scope.selected_ = data;
}
});
}
// get all posts // try some function to get a single produt from server
$scope.getPosts = function(){
Climbs.getPosts()
.success(function (data) {
// data = feed.json file
var climbs = [];
data.areas.map(function(area) {
if (area._id === areaId) {
climbs = area.climbs;
}
});
$scope.selectClimb(climbs);
})
.error(function (error) {
$scope.items = [];
});
}
$scope.getPosts();
}
])
And I ned to add this to it:
.controller('MyCtrl', function($scope, $ionicModal) {
$ionicModal.fromTemplateUrl('test-modal.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
$scope.modal = modal;
});
$scope.openModal = function() {
$scope.modal.show();
};
$scope.closeModal = function() {
$scope.modal.hide();
};
//Cleanup the modal when we're done with it!
$scope.$on('$destroy', function() {
$scope.modal.remove();
});
// Execute action on hide modal
$scope.$on('modal.hidden', function() {
// Execute action
});
// Execute action on remove modal
$scope.$on('modal.removed', function() {
// Execute action
});
});
When I try to add this to the code it breaks it. I nee to either add it as another function or whatever is needed to add it to the code.
Thanks so much
Assuming that you want to merge 'MyCtrl functions into ClimbController then
.controller('ClimbController', ['$scope', '$stateParams', 'Climbs','$ionicModal', function($scope, $stateParams, Climbs,$ionicModal) {
var climb_id = $stateParams.climbId;
var areaId = $stateParams.areaId;
if (!isNaN(climb_id)) {
climb_id = parseInt(climb_id);
}
if (!isNaN(areaId)) {
areaId = parseInt(areaId);
}
$scope.selected_ = {};
$scope.items = [];
$scope.details = true;
// looping though all data and get particular product
$scope.selectClimb = function(areas){
areas.forEach(function(data) {
if(data._id == climb_id){
$scope.selected_ = data;
}
});
}
// get all posts // try some function to get a single produt from server
$scope.getPosts = function(){
Climbs.getPosts()
.success(function (data) {
// data = feed.json file
var climbs = [];
data.areas.map(function(area) {
if (area._id === areaId) {
climbs = area.climbs;
}
});
$scope.selectClimb(climbs);
})
.error(function (error) {
$scope.items = [];
});
}
$scope.getPosts();
$ionicModal.fromTemplateUrl('test-modal.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
$scope.modal = modal;
});
$scope.openModal = function() {
$scope.modal.show();
};
$scope.closeModal = function() {
$scope.modal.hide();
};
//Cleanup the modal when we're done with it!
$scope.$on('$destroy', function() {
$scope.modal.remove();
});
// Execute action on hide modal
$scope.$on('modal.hidden', function() {
// Execute action
});
// Execute action on remove modal
$scope.$on('modal.removed', function() {
// Execute action
});
}])

Angular. Authentication is not checked

Authentication is not checked in my angular app. User should not have access to "car" & "profile" views without login but now i can get to it. I've added "secure" property to the pages that should be hidden from non-authenticated user. I've added check for apprun in app.js. But it does not work.
here's services.js
'use strict';
angular.module('myApp')
.service('carsSrv', function () {
var carList = [];
var addUserCar = function (currObj, title, color, description, image) {
currObj = {
title: title,
color: color,
descriptiopn: description,
image: image
};
/* console.log("Car Added: " + currObj.id + "\n" + currObj.title + "\n" + currObj.color + "\n" + currObj.description + "\n" + currObj.image);*/
carList.push(currObj);
console.log(carList);
};
var getCars = function () {
console.log("User cars");
console.log(carList);
return carList;
};
return {
addUserCar: addUserCar,
getCars: getCars
}
})
.service('userSrv', userSrv)
.provider('storageSrv',storageSrv);
function userSrv(storageSrv, carsSrv) {
var user = {name: '', cars: carsSrv.carList };
this.getUser = function() {
return user;
};
this.getUserName = function () {
return user.name;
};
this.login = function(){
user.name = 'test name';
user.cars = init();
storageSrv.updateData(user);
return true;
}
this.logout = function(){
user.name = '';
user.cars = [];
alert('User logs out');
storageSrv.updateData(user);
}
this.checkLoginUser = function(){
return user.name !='';
}
this.getUserFeatures = function(){
return user.features;
}
this.registration = function(){
user.name = name;
user.cars = init();
}
function init(){
return storageSrv.getData();
}
}
function storageSrv(){
var storageName = 'cars';
return {
configStorageName : configStorageName,
$get:$get
};
function configStorageName(name){
if(name){
storageName = name;
return this;
}
else{
return storageName;
}
}
function $get(){
function updateStorage(data){
localStorage.setItem(storageName, data);
}
function getStorage(){
return localStorage.getItem(storageName);
}
function updateData(data){
console.log('storageName ' + storageName);
updateStorage(JSON.stringify(data));
}
function getData(){
console.log('storageName ' + storageName);
var data = getStorage();
return JSON.parse(data) || [];
}
return {
updateData: updateData,
getData:getData
}
}
};
and here's app.js
'use strict';
// Declare app level module which depends on views, and components
angular.module('myApp', [
'ngRoute'
])
.constant('STORAGE_NAME', 'USER_CARS')
.config(configStorage)
.config(configRoutes)
.controller('carsCtrl', ['$scope', '$http', 'carsSrv',
function($scope, $http, carsSrv) {
$scope.view = "Cars";
$http.get('cars/cars.json')
.success(function(data) {
$scope.cars = data;
$scope.addCar = function(id, title, color, description, image) {
carsSrv.addUserCar(id, title, color, description, image);
};
})
.error(function() {
alert("can not get data from cars.json");
});
}
])
.controller('homeCtrl', ['$scope',
function($scope) {
$scope.view = "Home";
}
])
.controller('loginCtrl', ['userSrv', '$scope',
function(userSrv, $scope) {
$scope.view = "Login";
$scope.userLogin = function() {
userSrv.login();
}
$scope.userLogout = function() {
userSrv.logout();
}
}
])
.controller('profileCtrl', ['$scope', 'carsSrv',
function($scope, carsSrv) {
$scope.view = "Profile";
$scope.userCars = carsSrv.getCars();
}
]);
function configStorage(storageSrvProvider, STORAGE_NAME) {
console.log(storageSrvProvider);
storageSrvProvider.configStorageName(STORAGE_NAME);
}
function configRoutes($routeProvider) {
$routeProvider
.when('/cars', {
templateUrl: 'views/cars.html',
controller: 'carsCtrl',
secure: true
})
.when('/profile', {
templateUrl: 'views/profile.html',
controller: 'profileCtrl',
secure: true
})
.when('/home', {
templateUrl: 'views/home.html',
controller: 'homeCtrl',
secure: false
})
.when('/login', {
templateUrl: 'views/login.html',
controller: 'loginCtrl',
secure: false
})
.otherwise({
redirectTo: '/home'
});
}
var appRun = function($rootScope, $location, $userSrv) {
$rootScope.on('$routeChangeStart', function(event, next) {
if (next.secure && !userSrv.checkLoginUser()) {
$location.path('/login');
}
});
};
Your not really running the code appRun. Try adding this last line to your module declaration:
angular.module('myApp', [
'ngRoute'
])
.constant('STORAGE_NAME', 'USER_CARS')
.config(configStorage)
.config(configRoutes)
.run(appRun);
Also, because appRun is a variable containing an anonymous function, and not a function named appRun, by the time you call the run(appRun) (at the beginning of the file) the variable is defined but still undefined. That is why the function is not running.
Also, when listening to the event, you're using a function $rootScope.on(), instead of the correct name $rootScope.$on(). Apart from that, I tested it on my computed and it seems to be working.
function checkRoute ( userSrv, $location, current ) {
if (current.secure && !userSrv.checkLoginUser()) {
$location.path('/login');
}
}
function appRun ($rootScope, $route, $location, userSrv) {
$rootScope.$on('$routeChangeStart', function(event, next) {
checkRoute(userSrv, $location, next);
});
$rootScope.$on('sessionLogout', function () {
checkRoute(userSrv, $location, $route.current);
});
};
Update: For the logout to work, one strategy is to emit an event when logging out and then listen for that even and do the same check to see if the page is secure or not.
function userSrv($rootScope, storageSrv, carsSrv) {
//...
this.logout = function(){
user.name = '';
user.cars = [];
alert('User logs out');
storageSrv.updateData(user);
// Emit an event notifying the application that
// the user has logged out
$rootScope.$emit('sessionLogout');
}
//...
}

$http.get to resource in angularjs

How would i change the following code form $http.get to a $resource
//The created resource (not using it for now)
hq.factory('LogsOfUser', function ($resource) {
return $resource('/HQ/Graph/GetLoggedinTimes?userName=:userName', {
userName: '#userName'
})
});
//The Controller
var ModalViewLogActionsCtrl = function ($scope, $http, $log, LogsOfUser, $modal) {
$scope.openLogs = function (userName) {
$http.get("/HQ/Graph/GetLoggedinTimes?userName=" + userName).success(function (data) {
var modalInstance = $modal.open({
templateUrl: 'LogView.html',
controller: 'ModalLogViewInstance',
resolve: {
items: function () {
//$scope.items = data;
$log.log(data);
$scope.items = data;
return $scope.items; //return data;
},
userName: function () {
return userName;
}
}
});
}).error(function () {
alert("eror :(");
});;
};
};
You've already done most of the work. All you need now is to call the service inside the controller :
LogsOfUser.query({
userName: userName
}, function success(data) {
//your code
}, function err() {
alert("Error")
});
Use query to get an array of data, and get to get a single document.
Here is a example how to call a resource from a controller:
app.controller('MainCtrl', function($scope, $resource) {
var userName = 'Bob';
var LoggedinTimes = $resource('/HQ/Graph/GetLoggedinTimes');
var data = LoggedinTimes.get({userName : userName}, function () {
console.log(data);
});
});
First, you would want to move data-related logic behind a Service, so your controller doesn't know about server-specifics. More importantly, your Service becomes reusable as all services in AngularJS are global singletons. your controller stays small, as it should be.
Next, your controller would call getLoggedIntimes() and work with the outcome as if the data is there. The result of a $resource.get() or similar functions return an empty object or array which fills itself when the REST call returns with data.
In your service you would do the actual $resource.get().
something along the lines of the following pseudo code:
//The Controller
var ModalViewLogActionsCtrl = function ($scope, MyService, $log, LogsOfUser, $modal) {
$scope.openLogs = function (userName) {
var items = MyService.getLoggedInTimes(userName);
var modalInstance = $modal.open({
templateUrl: 'LogView.html',
controller: 'ModalLogViewInstance',
resolve: {
items: function () {
$scope.items = items;
return $scope.items;
},
userName: function () {
return userName;
}
}
});
};
};
app.service('MyService', function ($resource) {
var loggedInResource = $resource('/HQ/Graph/GetLoggedinTimes/:userName');
return {
getLoggedInTimes: functio(username) {
return loggedInResource.get({
username: username
});
}
};
});

Prevent multiple ajax calls when re-using a controller/factory

just starting out really with Angular and need some advice regarding preventing repeated ajax requests for the same data when re-using a controller with multiple view.
So I have say 6 views all referencing the same controller but different views
app.js
(function() {
var app = angular.module('myApp', ['ngRoute','ui.unique']);
app.config(function ($routeProvider) {
// Routes
$routeProvider
.when('/',
{
controller: 'SamplesController',
templateUrl: 'app/views/home.html'
})
.when('/view2/',
{
controller: 'SamplesController',
templateUrl: 'app/views/main.html'
})
.when('/view3/:rangeName',
{
controller: 'SamplesController',
templateUrl: 'app/views/samples.html'
})
.when('/view4/:rangeName',
{
controller: 'SamplesController',
templateUrl: 'app/views/samples.html'
})
.when('/view5/',
{
controller: 'SamplesController',
templateUrl: 'app/views/basket.html'
})
.when('/view6/',
{
controller: 'SamplesController',
templateUrl: 'app/views/lightbox.html'
})
.otherwise({ redirectTo: '/' });
});
}());
samplesController.js
(function() {
var SamplesController = function ($scope, SamplesFactory, appSettings, $routeParams) {
function init() {
// back function
$scope.$back = function() {
window.history.back();
};
// app settings
$scope.settings = appSettings;
// samples list
SamplesFactory.getSamples()
.success(function(data){
var returnSamples = [];
for (var i=0,len=data.length;i<len;i++) {
if (data[i].range === $routeParams.rangeName) {
returnSamples.push(data[i]);
}
}
$scope.samples = returnSamples;
})
.error(function(data, status, headers, config){
// return empty object
return {};
});
// variables for both ranges
$scope.rangeName = $routeParams.rangeName;
// click to change type
$scope.populate = function(type) {
$scope.attributeValue = type;
};
};
init();
};
SamplesController.$inject = ['$scope','SamplesFactory', 'appSettings', '$routeParams'];
angular.module('myApp').controller('SamplesController', SamplesController);
}());
samplesFactory.js
(function () {
var SamplesFactory = function ($http) {
var factory = {};
factory.getSamples = function() {
return $http.jsonp('http://www.website.com/app/index.php?callback=JSON_CALLBACK');
};
return factory;
};
SamplesFactory.$inject = ['$http'];
angular.module('myApp').factory('SamplesFactory', SamplesFactory);
}());
So with this - every time a new view is loaded the ajax request is made again - how would I re-purpose to have only a single request happen?
As always thanks in advance
Carl
UPDATE: Answer marked below but I also had success by changing the "cache" config item/property (whatever its called) to true in the jsonp request
return $http.jsonp('http://www.website.com/app/index.php?callback=JSON_CALLBACK',{cache: true});
You could change your factory in this way:
(function () {
var SamplesFactory = function ($http) {
var factory = {},
samples = $http.jsonp('http://www.website.com/app/index.php?callback=JSON_CALLBACK');
factory.getSamples = function() {
return samples;
};
return factory;
};
SamplesFactory.$inject = ['$http'];
angular.module('myApp').factory('SamplesFactory', SamplesFactory);
}());
Now getSamples() returns a promise that you should manage in your controllers.

Resources