How to detect when ionicSideMenu is open? - angularjs

http://codepen.io/leongaban/pen/PPLVNY?editors=101
I'm trying to have a flag var change when the left panel is open in an ionic app.
I found this and tried implementing it, but the variable doesn't change and I don't see the console.log statement.
Markup
<script id="templates/home.html" type="text/ng-template">
<ion-view view-title="Welcome">
<ion-content class="padding">
<h1>{{changeMe}}</h1>
<p>Swipe to the right to reveal the left menu.</p>
<p>(On desktop click and drag from left to right)</p>
</ion-content>
</ion-view>
</script>
Controller
.controller('MainCtrl', function($scope, $ionicSideMenuDelegate, $ionicPlatform) {
$scope.changeMe = "This should change if left panel is open"
$scope.attendees = [
{ firstname: 'Nicolas', lastname: 'Cage' },
{ firstname: 'Jean-Claude', lastname: 'Van Damme' },
{ firstname: 'Keanu', lastname: 'Reeves' },
{ firstname: 'Steven', lastname: 'Seagal' }
];
$scope.toggleLeft = function() {
$ionicSideMenuDelegate.toggleLeft();
};
$ionicPlatform.registerBackButtonAction(function (event) {
$ionicSideMenuDelegate.toggleLeft();
$ionicSideMenuDelegate.$getByHandle('sideMenu').toggleLeft();
$timeout ( function() {
$scope.changeMe = "CHANGED! Left panel is open!";
console.log ("Status of SIDE MENU IS : " + $ionicSideMenuDelegate.$getByHandle('sideMenu').isOpen());
},1000);
}, 100);
})
Also tried this:
.run(function($ionicPlatform, $ionicSideMenuDelegate) {
$ionicPlatform.registerBackButtonAction(function(e) {
e.preventDefault();
if (!$ionicSideMenuDelegate.isOpen()) {
console.log('isOPEN!');
}
if (!$ionicSideMenuDelegate.isOpenLeft()) {
console.log('OPEN!');
$ionicSideMenuDelegate.toggleLeft();
} else {
console.log('Closed!');
}
}, 1000);
})

isOpenLeft() is working with me. :)
I'm using the below code to detect open or close slide menu.
$scope.$watch(function () {
return $ionicSideMenuDelegate.isOpenLeft();
},
function (isOpen) {
if (isOpen){
console.log("open");
} else{
console.log("close");
}
});

getOpenRatio worked! isOpen didn't work and isOpenLeft did not work for me.
$scope.$watch(function () {
return $ionicSideMenuDelegate.getOpenRatio();
},
function (ratio) {
if (ratio === 1){
console.log('ratio is true');
$scope.isActive= true;
} else{
$scope.isActive = false;
console.log('ratio is false');
}
});
UPDATE: Just fixed it in my actual app as well! I had 2 ion-side-menus instead of just 1.
<ion-side-menus class="ion-home">
<!-- <ion-side-menus enable-menu-with-back-views="false"> -->

Related

How to use Angular geolocation directive with google map ?

I am using Angular geolocation for get location. Its returning latitude and longitude of location. I want to show map using this latitude and longitude. Also want to show a circle with 5 km. take a look of my code index.html
<html>
<head>
<title>ngGeolocation</title>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.3/angular.js"></script>
<script src="./ngGeolocation.js"></script>
<script src="./index.js"></script>
</head>
<body ng-app="geolocationDemo">
<div ng-controller="AppController">
<h1>Basic (fetch once)</h1>
Latitude: {{location.coords.latitude}}
<br />
Longitude: {{location.coords.longitude}}
<br />
</div>
</body>
</html>
Index.js
angular
.module('geolocationDemo', ['ngGeolocation'])
.controller('AppController', function($scope, $geolocation){
$scope.$geolocation = $geolocation
// basic usage
$geolocation.getCurrentPosition().then(function(location) {
$scope.location = location
});
// regular updates
$geolocation.watchPosition({
timeout: 60000,
maximumAge: 2,
enableHighAccuracy: true
});
$scope.coords = $geolocation.position.coords; // this is regularly updated
$scope.error = $geolocation.position.error; // this becomes truthy, and has 'code' and 'message' if an error occurs
//console.log($scope.coords);
});
ngGeolocation.js
angular
.module('ngGeolocation', [])
.factory('$geolocation', ['$rootScope', '$window', '$q', function($rootScope, $window, $q) {
function supported() {
return 'geolocation' in $window.navigator;
}
var retVal = {
getCurrentPosition: function(options) {
var deferred = $q.defer();
if(supported()) {
$window.navigator.geolocation.getCurrentPosition(
function(position) {
$rootScope.$apply(function() {
retVal.position.coords = position.coords;
deferred.resolve(position);
});
},
function(error) {
$rootScope.$apply(function() {
deferred.reject({error: error});
});
}, options);
} else {
deferred.reject({error: {
code: 2,
message: 'This web browser does not support HTML5 Geolocation'
}});
}
return deferred.promise;
},
watchPosition: function(options) {
if(supported()) {
if(!this.watchId) {
this.watchId = $window.navigator.geolocation.watchPosition(
function(position) {
$rootScope.$apply(function() {
retVal.position.coords = position.coords;
delete retVal.position.error;
$rootScope.$broadcast('$geolocation.position.changed', position);
});
},
function(error) {
$rootScope.$apply(function() {
retVal.position.error = error;
delete retVal.position.coords;
$rootScope.$broadcast('$geolocation.position.error', error);
});
}, options);
}
} else {
retVal.position = {
error: {
code: 2,
message: 'This web browser does not support HTML5 Geolocation'
}
};
}
},
position: {}
//console.log(position);
};
return retVal;
}]);
How to i can do it ? Please suggest me some solutions.
Have a look at angular-google-maps, you should be able to create the map and circle:
http://angular-ui.github.io/angular-google-maps/

Angular $watch function after change variable

I´m trying to build a delayed message box. I observe that apply is called when the app is started, as describe in the API docs. But when the observed value is changed, it isn´t called. The MessageCtrl is inner controller. Why isn´t watch called after changing message var?
angular.module('myApp',[]).controller('MessageCtrl', function($scope) {
$scope.getMessage = function() {
setTimeout(function() {
$scope.$parent.message = {text : ""};
$scope.$apply(function() {
console.log('message:' + $scope.$parent.message.text);
});
}, 2000);
}
$scope.getMessage();
})
.controller('MainCtrl',function($scope){
$scope.message={text:"oi"};
$scope.$watch("message", function(newValue, oldValue){
console.log("watch " + $scope.message.text);
});
});
The inner controller MessageCtrl will get the text message and show it for 2 seconds.
<body ng-app="myApp" ng-controller="MainCtrl">
<div ng-controller="MessageCtrl">
Message:{{message.text}}
</div>
</body>
As far as I can tell your code does work. You are however using $apply incorrectly. $apply lets you inform angular that you are changing state outside of the usual methods and that is should thus re-evaluate bindings etc. So you should be using
$scope.$apply(function() { $scope.$parent.message = {text: 'new message'}; });
angular.module('myApp', []).controller('MessageCtrl', function($scope) {
$scope.getMessage = function() {
setTimeout(function() {
$scope.$apply(function() {
$scope.$parent.message = {
text: "new message"
};
console.log('message:' + $scope.$parent.message.text);
});
}, 2000);
}
$scope.getMessage();
})
.controller('MainCtrl', function($scope) {
$scope.message = {
text: "oi"
};
$scope.$watch("message", function(newValue, oldValue) {
console.log("watch " + $scope.message.text);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MainCtrl">
<div ng-controller="MessageCtrl">
Message:{{message.text}}
</div>
</div>
One thing of note, you should really use the angular $timeout service which allows you to set timeouts in your app, but you don't have to handle calling $apply.
angular.module('myApp', []).controller('MessageCtrl', function($scope, $timeout) {
$scope.getMessage = function() {
$timeout(function() {
$scope.$parent.message = {
text: "new message"
};
console.log('message:' + $scope.$parent.message.text);
}, 2000);
}
$scope.getMessage();
})
.controller('MainCtrl', function($scope) {
$scope.message = {
text: "oi"
};
$scope.$watch("message", function(newValue, oldValue) {
console.log("watch " + $scope.message.text);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MainCtrl">
<div ng-controller="MessageCtrl">
Message:{{message.text}}
</div>
</div>
You need to use $scope.apply method because setTimeout function is not angular native function :
setTimeout(function() {
$scope.apply({
$scope.$parent.message = {text : ""}; $scope.$apply(function() { console.log('message:' + $scope.$parent.message.text); });}) ;}, 2000);
Alternatively you can also use $timeout inbuilt-service in angular like this :
angular.module('myApp',[]).controller('MessageCtrl', function($scope, , $timeout) { $scope.getMessage = function() { $, $timeout(function() { $scope.$parent.message = {text : ""}; $scope.$apply(function() { console.log('message:' + $scope.$parent.message.text); }); }, 2000); } $scope.getMessage(); })
use $timeout instead $apply that executes $apply implicity
angular.module('myApp',[]).controller('MessageCtrl', function($scope, $timeout) {
$scope.getMessage = function() {
$timeout(function() {
$scope.$parent.message = {text : ""};
$scope.$apply(function() {
console.log('message:' + $scope.$parent.message.text);
});
}, 2000);
}
$scope.getMessage();
})

How to change the text of button three times in angular?

Hi Friends here i have done the code for change text of button, like if i press the button the text of the button will change. But i need the text of the button to be change one more time,
eg: initially "Button1" -->(click)-->"Button2" -->(click)-->"Button3".
I need button3 also.
please reffer:http://jsfiddle.net/Ljrpd/17/
var app = angular.module('my-app', [], function () {
})
app.controller('AppController', function ($scope) {
$scope.toggle = true;
$scope.$watch('toggle', function(){
$scope.toggleText = $scope.toggle ? 'Button1' : 'Button2';
})
})
Some one help me out in this issue.
Thanks
You don't need toggle variable, you can store selected index as suggested by Peter. I would also add check for last selection:
app.controller('AppController', function ($scope) {
$scope.buttonIndex = 0;
$scope.buttonNames = ['Button 1', 'Button 2', 'Button 3', 'Last Button']
$scope.changeText = function() {
if ($scope.buttonIndex === $scope.buttonNames.length - 1) {
$scope.buttonIndex = 0;
} else {
$scope.buttonIndex += 1;
}
};
});
JS Fiddle
Try my modification:
http://jsfiddle.net/Ljrpd/18/
<button ng-click="toggle = !toggle">{{buttonNames[buttonIndex]}}</button>
var app = angular.module('my-app', [], function () {
})
app.controller('AppController', function ($scope) {
$scope.toggle = true;
$scope.buttonIndex = 0;
$scope.buttonNames = ['first', 'second', 'third']
$scope.$watch('toggle', function(){
$scope.buttonIndex += 1;
})
})
And here's a version without a watch:
http://jsfiddle.net/russf6s9/1/
<button ng-click="incrementButton()">{{buttonNames[buttonIndex]}}</button>
var app = angular.module('my-app', [], function () {
})
app.controller('AppController', function ($scope) {
$scope.buttonIndex = 0;
$scope.incrementButton = function() {
$scope.buttonIndex += 1;
}
$scope.buttonNames = ['first', 'second', 'third']
})
Use a directive:
app.directive('changeText', function(){
return {
restrict: "A",
scope: {
changeText: "="
},
link: function(scope, element, attr) {
scope.index = 0;
element.html(scope.changeText[0]);
element.on('click', function(){
scope.index = (scope.index + 1) % scope.changeText.length;
element.html(scope.changeText[scope.index]);
})
}
};
})
Then in your html:
<body ng-controller="MainCtrl as ctrl">
<button change-text="ctrl.textValues"></button>
</body>
Plnkr
Script:
.controller('myctrl', function ($scope) {
$scope.btntext='button_1';
$scope.changetext = function () {
$scope.btntext = ($scope.btntext=='button_1')?'button_2':($scope.btntext=='button_2')?'button_3':'button_1';
}
});
Markup:
<input type="button" ng-click="changetext()" ng-value="btntext"/>
View in Plunker

How to dismiss an angularjs alert when user changes route/state

I am using this angular js service/directive github pageto display alerts. An issue has been opened relating to the question I am asking but it has not been addressed by the developer.
i want first alert shown when user logs in to disappear when the user clicks logout but the alerts are stacking up on top of each other.
Here is a fiddle although I could not replicate the issue but it shows the structure of my code. fiddle
html:
<body ng-app="app">
<mc-messages></mc-messages>
<button ng-click="login()">Login</button>
<button ng-click="logout()">Logout</button>
</body>
js:
/*jshint strict:false */
'use strict';
var app = angular.module('app', ['MessageCenterModule']);
app.controller(function ($scope, messageCenterService, $location) {
$scope.login = function () {
$location.path('/');
messageCenterService.add('success',
'You are now loggedin!', {
status: messageCenterService.status.next
});
};
$scope.logout = function () {
$location.path('login');
messageCenterService.add('success',
'You are now loggedout!', {
status: messageCenterService.status.next
}
};
});
// Create a new angular module.
var MessageCenterModule = angular.module('MessageCenterModule', []);
// Define a service to inject.
MessageCenterModule.
service('messageCenterService', ['$rootScope', '$sce', '$timeout',
function ($rootScope, $sce, $timeout) {
return {
mcMessages: this.mcMessages || [],
status: {
unseen: 'unseen',
shown: 'shown',
/** #var Odds are that you will show a message and right after that
* change your route/state. If that happens your message will only be
* seen for a fraction of a second. To avoid that use the "next"
* status, that will make the message available to the next page */
next: 'next',
/** #var Do not delete this message automatically. */
permanent: 'permanent'
},
add: function (type, message, options) {
var availableTypes = ['info', 'warning', 'danger', 'success'],
service = this;
options = options || {};
if (availableTypes.indexOf(type) === -1) {
throw "Invalid message type";
}
var messageObject = {
type: type,
status: options.status || this.status.unseen,
processed: false,
close: function () {
return service.remove(this);
}
};
messageObject.message = options.html ? $sce.trustAsHtml(message) : message;
messageObject.html = !! options.html;
if (angular.isDefined(options.timeout)) {
messageObject.timer = $timeout(function () {
messageObject.close();
}, options.timeout);
}
this.mcMessages.push(messageObject);
return messageObject;
},
remove: function (message) {
var index = this.mcMessages.indexOf(message);
this.mcMessages.splice(index, 1);
},
reset: function () {
this.mcMessages = [];
},
removeShown: function () {
for (var index = this.mcMessages.length - 1; index >= 0; index--) {
if (this.mcMessages[index].status == this.status.shown) {
this.remove(this.mcMessages[index]);
}
}
},
markShown: function () {
for (var index = this.mcMessages.length - 1; index >= 0; index--) {
if (!this.mcMessages[index].processed) {
if (this.mcMessages[index].status == this.status.unseen) {
this.mcMessages[index].status = this.status.shown;
} else if (this.mcMessages[index].status == this.status.next) {
this.mcMessages[index].status = this.status.unseen;
}
this.mcMessages[index].processed = true;
}
}
},
flush: function () {
$rootScope.mcMessages = this.mcMessages;
}
};
}]);
MessageCenterModule.
directive('mcMessages', ['$rootScope', 'messageCenterService', function ($rootScope, messageCenterService) {
/*jshint multistr: true */
var templateString = '\
<div id="mc-messages-wrapper">\
<div class="alert alert-{{ message.type }} {{ animation }}" ng-repeat="message in mcMessages">\
<a class="close" ng-click="message.close();" data-dismiss="alert" aria-hidden="true">×</a>\
<span ng-switch on="message.html">\
<span ng-switch-when="true">\
<span ng-bind-html="message.message"></span>\
</span>\
<span ng-switch-default>\
{{ message.message }}\
</span>\
</div>\
</div>\
';
return {
restrict: 'EA',
template: templateString,
link: function (scope, element, attrs) {
// Bind the messages from the service to the root scope.
messageCenterService.flush();
var changeReaction = function (event, to, from) {
// Update 'unseen' messages to be marked as 'shown'.
messageCenterService.markShown();
// Remove the messages that have been shown.
messageCenterService.removeShown();
$rootScope.mcMessages = messageCenterService.mcMessages;
messageCenterService.flush();
};
$rootScope.$on('$locationChangeStart', changeReaction);
scope.animation = attrs.animation || 'fade in';
}
};
}]);
Hope this is clear enough for someone to help me. If not let me know and I can try to clarify.

How do I use ng-grid with Angular HotTowel

I am using John Papa's Angular HotTowel and I don't know how to incorporate Angulars ng-grid into the html. Here is what I've added thanks to wonderful help from stondo. Breeze seems to be adding extra information that is no allowing ng-grid to render the data in the grid. Is there a way to strip the extra info that breeze sends or a work around for ng-grid to behave correctly with breeze data?
angular.module('app').controller(controllerId,
['common', 'datacontext','$scope', '$http', grid2]);
function grid2(common, datacontext, $scope, $http) {
.....
.....
} else {
$http.get('/breeze/Breeze/NoBadgePersonnels').success(function (largeLoad) {
$scope.setPagingData(largeLoad, page, pageSize);
});
activate();
function activate() {
common.activateController([mockData()], controllerId)
.then(function() { log('Activated Grid View'); });
function mockData() {
return datacontext.getEmployeePartialsNoBadges().then(function (data) {
return vm.grid2 = data.results;
});
}
}
Additional information
Datacontext.js looks as follows:
(function () {
'use strict';
var serviceId = 'datacontext';
angular.module('app').factory(serviceId,
['common', 'config', 'entityManagerFactory', datacontext]);
function datacontext(common, config, emFactory ) {
var EntityQuery = breeze.EntityQuery;
var getLogFn = common.logger.getLogFn;
var log = getLogFn(serviceId);
var logError = getLogFn(serviceId, 'error');
var logSuccess = getLogFn(serviceId, 'success');
var manager = emFactory.newManager();
var $q = common.$q;
var service = {
getPeople: getPeople,
getMessageCount: getMessageCount,
getEmployeePartials: getEmployeePartials,
getEmployeePartialsNoBadges: getEmployeePartialsNoBadges
};
var entityNames = {
personnel: 'Personnel'
};
return service;
function getEmployeePartialsNoBadges() {
var orderBy = 'lname';
var employees; //variable to hold employees once we get them back
//use query using Employees resource
return EntityQuery.from('NoBadgePersonnels')
.select('id, fname, lname, class, zip, cntySnrDte')
.orderBy(orderBy)
.toType('Personnel')
.using(manager).execute()
.then(querySucceeded, _queryFailed)
function querySucceeded(data) {
employees = data.results;
log('Retrieved [Employee Partials] from remote data source', employees.length, true);
//log('Retrieved [Employee Partials] from remote data source');
return employees;
}
}
function _queryFailed(error) {
var msg = config.appErrorPrefix + 'Error retrieving data from entityquery' + error.message;
logError(msg, error);
throw error;
}
=================================
It seems like the grid sees 5 items that I queried for, however the items don't want to display on the cells. Red arrow indicates that it allocated 5 rows, and green arrow indicates that I have selected one of the rows. Still doesn't display the records.
thanks
nick
I had to modify John Papa's Hottowel.Angular template, because it wasn't working as expected with latest angular/breeze versions. I'll later share a github link and a blog post about that.
I was able to get ng-grid working just adding $scope and $http to the controller. Read the comment inside the code block to see how it could be entirely done without inject $http.
(function () {
'use strict';
var controllerId = 'corrieri';
angular.module('app').controller(controllerId, ['common', 'datacontext', '$scope', '$http', corrieri]); //'$http', '$scope',
function corrieri(common, datacontext, $scope, $http) { //,$http, $scope
var getLogFn = common.logger.getLogFn;
var log = getLogFn(controllerId);
var vm = this;
$scope.corrieriList = [];
vm.corrieri = [];
vm.news = {
title: 'Corrieri',
description: 'Lista Corrieri'
};
vm.title = 'Corrieri';
//ng-grid test
$scope.filterOptions = {
filterText: "",
useExternalFilter: false
};
$scope.totalServerItems = 0;
$scope.pagingOptions = {
pageSizes: [10, 20, 30],
pageSize: 10,
currentPage: 1
};
$scope.setPagingData = function (data, page, pageSize) {
data = data.map(function (item) {
return {
PK_ID: item.PK_ID,
Ragione_Sociale: item.Ragione_Sociale,
Telefono: item.Telefono,
Nazionalita: item.Nazionalita,
Indirizzo: item.Indirizzo,
Cap: item.Cap,
Provincia: item.Provincia,
Descrizione: item.Descrizione
};
});
var pagedData = data.slice((page - 1) * pageSize, page * pageSize);
$scope.corrieriList = pagedData; //.results;
$scope.totalServerItems = data.length;
if (!$scope.$$phase) {
$scope.$apply();
}
};
$scope.getPagedDataAsync = function (pageSize, page, searchText) {
setTimeout(function () {
var data;
if (searchText) {
var ft = searchText.toLowerCase();
$http.get('breeze/Corrieri/GetCorrieri').success(function (largeLoad) {
var myModArray = largeLoad.map(function (item) {
return {
Pk_ID: item.Pk_ID,
Ragione_Sociale: item.Ragione_Sociale,
Telefono: item.Telefono,
Nazionalita: item.Nazionalita,
Indirizzo: item.Indirizzo,
Cap: item.Cap,
Provincia: item.Provincia,
Descrizione: item.Descrizione
};
});
data = myModArray.filter(function (item) {
return JSON.stringify(item).toLowerCase().indexOf(ft) != -1;
});
$scope.setPagingData(data, page, pageSize);
});
} else {
$http.get('breeze/Corrieri/GetCorrieri').success(function (largeLoad) {
$scope.setPagingData(largeLoad, page, pageSize);
});
}
}, 100);
};
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage);
$scope.$watch('pagingOptions', function (newVal, oldVal) {
if (newVal !== oldVal && newVal.currentPage !== oldVal.currentPage) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
}
}, true);
$scope.$watch('filterOptions', function (newVal, oldVal) {
if (newVal !== oldVal) {
$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
}
}, true);
$scope.gridOptions = {
data: 'corrieriList',
enablePaging: true,
showFooter: true,
showFilter: true,
enableCellEdit: true,
enableColumnResize: true,
enableColumnReordering: true,
pinSelectionCheckbox: true,
totalServerItems: 'totalServerItems',
pagingOptions: $scope.pagingOptions,
filterOptions: $scope.filterOptions
};
//ng-grid test end
activate();
function activate() {
var promises = [getCorrieri()];
common.activateController(promises, controllerId)
.then(function () {
log('Activated Corrieri View');
});
}
//This function was used to get data using Breeze Controller
//and I was even able to use it to bind data to ng-grid
//calling the function getCorrieri inside my controller and binding
//gridOptions data to vm.corrieri or just the name of the function (in my case getCorrieri)
// $scope.gridOptions = { data: getCorrieri}
//Be aware that since we r using a Breeze Controller data retrieved have additional
//informations, so we have to remove those, if we bind using vm.corrieri.
//I found it easier to implement paging using $http and $scope, even though I think
//I could do it using only $scope and breeze.
//getCorrieri().then(function() {
// angular.forEach(vm.corrieri, function (cor) {
// delete cor._backingStore['$id'];
// delete cor._backingStore['$type'];
// $scope.corrieriList.push(cor._backingStore);
// });
//});
function getCorrieri() {
return datacontext.getCorrieri().then(function (data) {
return vm.corrieri = data.results;
});
}
}
})();
Below you can find my html for reference. Make sure to surround your's ng-grid div with data-ng-controller or just ng-controller='corrieri'
<section id="corrieri-view" class="mainbar" data-ng-controller="corrieri as vm">
<section class="matter">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="widget wgreen">
<div data-cc-widget-header title="Corrieri" allow-collapse="true"></div>
<div class="widget-content text-center text-info">
<div data-ng-controller='corrieri'>
<div class="gridStyle col-md-12" ng-grid="gridOptions">
</div>
</div>
<div class="widget-foot">
<div class="clearfix"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
</section>
Btw, don't forget to add 'ngGrid' to your modules list in app.js
var app = angular.module('app', ['ngGrid', other modules])
and also include ng-grid css and js in index.html (that is obvious, but better safe than sorry)
I struggled a few days to get this working properly, so I hope to help anyone out there having the same problem.
Try this out:
angular.module('app').controller(controllerId, ['common', 'datacontext', '$scope', grid]);
function grid(common, datacontext, $scope) {
$scope.gridOptions = {
data: 'vm.employees'
};
activate();
function activate() {
common.activateController([getEmployees()], controllerId)
.then(function () { log('Activated Grid View'); });
}
//get data for employees
function getEmployees() {
return datacontext.getEmployeePartialsNoBadges().then(function (mydata) {
return vm.employees = data;
});
}
}
here is an image of what I see
and here is the code I changed:
function getEmployees() {
return datacontext.getEmployeePartialsNoBadges().then(function (mydata) {
log(JSON.stringify(mydata));
return vm.employees = mydata.data;
});
Here is some additional info showing the data is coming through. Remote data source shows 1496 records. The preview for /breeze/breeze show data. I've blanked out sensitive info.
Here is the getEmployeePartialsNoBadges() method in my datacontext that was using entity framework:
function getEmployeePartialsNoBadges() {
var orderBy = 'lname';
var employees; //variable to hold employees once we get them back
//use query using Employees resource
return EntityQuery.from('NoBadgePersonnels')
.select('id, fname, lname, class, zip, cntySnrDte')
.orderBy(orderBy)
.toType('Personnel')
.using(manager).execute()
.then(querySucceeded, _queryFailed)
function querySucceeded(data) {
employees = data.results; //fillup the variable for employee with results
log('Retrieved [Employee Partials] from remote data source', employees.length, true);
//log('Retrieved [Employee Partials] from remote data source');
return employees;
}
}
============================== Nick ==============================
This is what my new mockup looks like now and I put this in datacontext calling it getPeople:
function getPeople() {
var people = [
{ firstName: 'John', lastName: 'Papa', age: 25, location: 'Florida' },
{ firstName: 'Ward', lastName: 'Bell', age: 31, location: 'California' },
{ firstName: 'Colleen', lastName: 'Jones', age: 21, location: 'New York' },
{ firstName: 'Madelyn', lastName: 'Green', age: 18, location: 'North Dakota' },
{ firstName: 'Ella', lastName: 'Jobs', age: 18, location: 'South Dakota' },
{ firstName: 'Landon', lastName: 'Gates', age: 11, location: 'South Carolina' },
{ firstName: 'Haley', lastName: 'Guthrie', age: 35, location: 'Wyoming' }
];
return $q.when(people);
}
I have reworked html and controller code to clean things up. The html is now call grid2.html and the controller is called grid2.js
(function () {
'use strict';
var controllerId = 'grid2';
angular.module('app').controller(controllerId,
['common', 'datacontext','$scope', grid2]);
function grid2(common, datacontext, $scope) {
var vm = this;
vm.grid2 = [];
$scope.gridOptions = {
data: 'vm.grid2'
};
var getLogFn = common.logger.getLogFn;
var log = getLogFn(controllerId);
vm.activate = activate;
vm.title = 'Grid2';
activate();
function activate() {
common.activateController([mockData()], controllerId)
.then(function() { log('Activated Grid View'); });
function mockData() {
return datacontext.getPeople().then(function (mydata) {
log(JSON.stringify(mydata));
return vm.grid2 = mydata.data;
});
}
}
}
})();
controller grid2.js
<section class="mainbar" data-ng-controller="grid2 as vm">
<section class="matter">
<div class="container">
<div class="row">
<div class="widget wgreen">
<div data-cc-widget-header title="Grid 2"></div>
<div class="widget-content user">
</div>
this is grid2 test
<div class="gridStyle" ng-grid="gridOptions"></div>
<div class="widget-foot">
<div class="clearfix"></div>
</div>
</div>
</div>
</div>
</section>
Here what the screen looks like now. still no data in the grid:
In the debug, the data property shows undefined still
The mydata does contain array of data
The vm is an empty array on the return statement
The vm.grid becomes empty after the return and I'm unsure what the vm is also
The console show data being present

Resources