The "with" binding of KnockoutJS in AngularJS? - angularjs

I have just switched from KnockoutJS to AngularJS and I am not able to find the KnockoutJS's "with" data-bind in AngularJS.
Here is the piece of code in KnockoutJS. The "with" binding creates a new binding context, so that descendant elements are bound in the context of a specified object.
<h1 data-bind="text: city"> </h1>
<p data-bind="with: coords">
Latitude: <span data-bind="text: latitude"> </span>,
Longitude: <span data-bind="text: longitude"> </span>
</p>
<script type="text/javascript">
ko.applyBindings({
city: "London",
coords: {
latitude: 51.5001524,
longitude: -0.1262362
}
});
</script>
Does AngularJS have anything like context?

Nothing like with that I know of.. this is the best I could do:
<h1>{{city}}</h1>
<p ng-repeat="c in [coords.or.possibly.deeper.in.tree]">
Latitude: {{c.latitude}},
Longitude: {{c.longitude}}
</p>

Create a custom directive that loops through the source object and creates corresponding properties on the directive's scope that are getter/setter references to the source object.
Check out this plunker.
directive module:
angular.module('koWith', [])
.directive('koWith', function () {
return {
controller: function ($scope, $attrs) {
var withObj = $scope.$parent[$attrs.ngWith];
function getter(prop) {
return this[prop];
}
function setter(val, prop) {
this[prop] = val;
}
for (var prop in withObj) {
if (withObj.hasOwnProperty(prop)) {
Object.defineProperty($scope, prop, {
enumerable: true,
configurable: true,
get: getter.bind(withObj, prop),
set: setter.bind(withObj, prop)
});
}
}
},
restrict: 'A',
scope: true
};
});
app module:
angular.module('myApp', [])
.controller('myController', function ($scope) {
$scope.customer = {
name: "Timmeh",
address: {
address1: "12 S Street",
address2: "",
city: "South Park",
state: "CO",
zipCode: "80440"
}
};
});
html:
<div ko-with="customer">
<h2>{{name}}</h2>
<div ko-with="address">
{{address1}}<br>
{{address2}}<br>
{{city}}, {{state}} {{zipCode}}
</div>
</div>
Explanation
In KnockoutJS, bindings keep the bindingContext and data separated so creating the with binding is trivial since it only needs to create a new child bindingContext from the current one and use the with object as its data value.
In AngularJS, a directive's scope is basically the bindingContext and data object rolled into one. When a new scope is created, in order to get the with-like behavior, the properties of the with object have to be referenced onto the newly created scope object.

Here is solution based on #nwayve, but it supports expressions in koWith and also it watches for updating property/expression specified in koWith:
.directive('koWith', function () {
return {
restrict: 'A',
scope: true,
controller: function ($scope, $attrs, $parse) {
var ScopePropertyDesc = function (prop) {
var self = this;
self.propName = prop;
self.parsed = $parse(prop);
self.enumerable = true;
self.configurable = true;
//self.writable = true;
self.get = function () {
var withObj = $scope.$parent[$attrs.koWith];
var res = self.parsed($scope.$parent, withObj);
return res;
};
self.set = function (newValue) {
var withObj = $scope.$parent[$attrs.koWith];
self.parsed.assign(withObj, newValue);
};
};
$scope.$parent.$watch($attrs.koWith, function (oldVal, newVal) {
var withObj = $scope.$parent[$attrs.koWith];
(function copyPropertiesToScope(withObj) {
for (var prop in withObj) {
if (withObj.hasOwnProperty(prop)) {
Object.defineProperty($scope, prop, new ScopePropertyDesc(prop));
}
};
})(withObj);
});
}
};
});

Related

scope variable not updating on view in ng-repeat

I have created a directive to handle multiple file uploads and defined a scope variable in the controller which holds the selected files. After selecting files the directive updates the parent scope with the file object.
I have used a loop to display multiple file uploads inputs.
Here is my controller
angular.module('myApp').controller('CompanyReviewsController', ['$state', '$scope', 'company', 'MediaUploadService', 'ReviewsService', 'rating_attributes', 'tags', function ($state, $scope, company, MediaUploadService, ReviewsService, rating_attributes, tags) {
$scope.company = company;
$scope.tags = tags;
$scope.rating_attributes = rating_attributes;
$scope.gallery = {
pictures: 0,
videos: 0,
};
$scope.reviewe_form_data = {
main_picture: null,
main_video: null,
review_subject: '',
review_description: '',
gallery: {
pictures: [],
videos: [],
}
};
}]);
Here is my Directive
angular.module('myApp').directive('fileUploadDirective', ['$parse', function ($parse) {
return {
scope:false,
link: function (scope, element, attrs) {
var model = $parse(attrs.fileUploadDirective);
var modelSetter = model.assign;
var valid_types = attrs.accept;
var valid_size = attrs.maxFileSize;//bytes
element.bind('change', function (event) {
var file = event.target.files[0];
scope.$apply(function () {
modelSetter(scope, file);
});
});}]);
Here is my view snippets
<div class="add-more-gallery-items add-more-gallery-images full-width clear-both pull-left">
<div class="gallery-item" ng-repeat="n in [].constructor($WU_APP_SETTINGS.pages_settings.write_review_page.gallery.pictures.maximum_pictures) track by $index">
{{reviewe_form_data.gallery}}
<div class="file-preview position-relative">
<span data-ng-if="reviewe_form_data.gallery.pictures[$index]" class="reset-image-preview wu-top-0-force wu-right-0-force" >
<img src="assets/images/close.png" alt="Close"/>
</span>
<img
alt="Review Gallery Image"
id="review-main-picture-{{$index}}"
data-file-preview-element="{{$WU_APP_SETTINGS.pages_settings.write_review_page.default_upload_image}}"
ng-src="{{$WU_APP_SETTINGS.pages_settings.write_review_page.default_upload_image}}"
/>
</div>
<input
file-upload-directive="reviewe_form_data.gallery.pictures[$index]"
data-max-file-size="{{$WU_APP_SETTINGS.pages_settings.write_review_page.gallery.pictures.max_picture_size}}"
accept="{{$WU_APP_SETTINGS.pages_settings.write_review_page.gallery.pictures.valid_picture_types}}"
class="upload"
type="file"
data-message-invalid-file="File not valid"
data-message-invalid-file-size="File size not valid"
data-file-preview-element="#review-main-picture-{{$index}}"
/>
</div>
</div>
In breif:
- I have a scope variable in controller
$scope.reviewe_form_data = {
main_picture: null,
main_video: null,
review_subject: '',
review_description: '',
gallery: {
pictures: [],
videos: [],
}
};
Above variable gets updated via directive(Working)
scope.$apply(function () {
modelSetter(scope, file);
});
But on view it shows empty object when i try to display the variable
{{reviewe_form_data.gallery}}

How to create angularjs custom directive for google location

I'm trying to create a directive to lookup google locations using <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true&libraries=places&language=en-US"></script> like this:
angular.module('MyApp').directive('locationPicker', function () {
return {
restrict: 'AE',
replace: true,
require: 'ngModel',
template: '<input id="{{id}}" type="text" class="{{class}}" placeholder="{{placeholder}}" />',
scope: {
id: '#',
class: '#',
placeholder: '#',
},
link: function ($scope, elm, attrs, controller) {
var autocomplete = new google.maps.places.Autocomplete(elm[0], {types: ['geocode']});
var componentForm = {
locality: 'long_name',
administrative_area_level_1: 'short_name',
country: 'long_name'
};
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place = autocomplete.getPlace();
var lat = place.geometry.location.lat();
var lng = place.geometry.location.lng();
var name = "";
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
if (name !== "") {
name += ", ";
}
var val = place.address_components[i][componentForm[addressType]];
name += val;
}
}
elm[0].value = name;
$scope.$apply(function () {
controller.$setViewValue({name: name, lat: lat, lng: lng});
});
});
}
};
});
And my input:
<input id="location" location-picker ng-model="location" class="form-control" placeholder="Project location" ng-required="true" />
In my controller:
$scope.location = {
name:null,
lat:null,
lng:null
};
Everything looks fine but when my component is first rendered, the value of the input is [Object object] instead of the place holder (Project Location).
What am I doing wrong?
Problem
You are binding ngModel to the location object, which renders as [object Object] when coerced to a string.
Solution
Since you are grabbing hold of the NgModelController in your directive, you can use its $formatters pipeline to transform the model value (location object with name, lat, lng properties) into the view value and the $render function to specify how to render the value if it is changed outside of the ngModel lifecycle.
Here is a working plunker: http://plnkr.co/edit/5HPFelbDFUrzeccGfgYx?p=preview. The crucial piece of code is
// triggered by $setViewValue
controller.$formatters.push(function (value) {
return value ? value.name : value;
});
// triggered by clear() from controller
controller.$render = function () {
input.value = controller.$modelValue.name;
};
I have also made the following modifications to your code:
Used location-picker as an element directive. input is not a good choice of element since it already has bindings to ngModel.
Removed replace: true. It is a deprecated configuration option in directives, and can cause some strange behaviors, since it tries to mix attributes of directive element and attributes of template element.
Removed elm[0].value = name;. This is handled by the lifecycle of the ngModel when you call $setViewValue.

angularjs googlemap not loading when trying to load in a modal

I am using AngularJS google maps to display map with markers.
The scenario is :
Initially Contact Details like Door no, Street, Area etc fields page will be displayed along with a static map. Once an edit button is clicked a pop-up with all the fields and map is displayed.
ex:
CODE:
html
<div class="row" ng-controller="userProfileController">
<ui-gmap-google-map center="center1" zoom="zoom1" pan="true" events="events">
<ui-gmap-markers models="models1" coords="'self'" options="'options'"></ui-gmap-markers>
</ui-gmap-google-map>
</div>
controller
$scope.center1 = {
latitude: lat,
longitude: lng
};
$scope.zoom1 = 8;
$scope.models1 = [{
id: 11445522,
latitude: lat,
longitude: lng,
options: {
title: "Current Location"
}
}];
Well everything works fine so far.
When edit is clicked i am trying to load another html in the modal that contains fields and a map. This time the map isn't loading. if I press 'F12' then map can be seen.
Code for popup:
html
<div class="col-sm-12">
<ui-gmap-google-map center="center3" zoom="zoom3" pan="true" events="events3" refresh="true">
<ui-gmap-markers doRebuildAll="true" doCluster="true" models="models3" coords="'self'" options="'options'"></ui-gmap-markers>
</ui-gmap-google-map>
controller
$scope.center3 = {latitude: 19.20742852680121,
longitude: 73.553466796875
};
$scope.zoom3 = 7;
$scope.models3 = [{
id: 5421222,
latitude: 19.20742852680121,
longitude: 73.553466796875,
options: {
title: "User Location"
}
}];
What might be the issue.? Can someone help me?
It displays like this:
I had a similar problem, but in my case, the user input an address and return the location. I found on the Internet the solution, and with some adjustments, I decided this way...
First, I create myController in app.js
app.controller('myController'), function ($scope) {
// my variable that's control my modal
$scope.showModal = false;
// my click event, like your 'Edit' button
$scope.createModal = function () {
$scope.showModal = true;
};
}
HTML index.html
<my-modal visible="showModal"></my-modal>
HTML modal.html
<div class="form-group">
<input type="text" class="form-control" ng-model="chosenPlace" details="chosenPlaceDetails" googleplace placeholder="Address"/>
<div class="map_container">
<div id="map_canvas" class="map_canvas"></div>
</div>
</div>
Then, in my modal.js, I created two Directive's
// Directive of Google Maps
angular.module('modal', [])
.directive('googleplace', function () {
return {
require: 'ngModel',
scope: {
ngModel: '=',
details: '=?'
},
controller: function ($scope) {
$scope.gPlace;
$scope.map;
$scope.marker;
$scope.initMap = function () {
// Set the initial lat and lng
var latlng = new google.maps.LatLng(-20.00, -47.00);
var options = {
zoom: 5,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
$scope.map = new google.maps.Map($("#map_canvas")[0], options);
$scope.marker = new google.maps.Marker({
map: $scope.map,
draggable: true,
});
$scope.marker.setPosition(latlng);
};
$scope.initMap();
},
link: function(scope, element, attrs, model) {
var options = {
types: ['geocode'],
componentRestrictions: { country: 'us' }
};
scope.gPlace = new google.maps.places.Autocomplete(element[0], options);
google.maps.event.addListener(scope.gPlace, 'place_changed', function() {
scope.$apply(function() {
google.maps.event.trigger(scope.map, 'resize');
var location = new google.maps.LatLng(scope.gPlace.getPlace().geometry.location.A, scope.gPlace.getPlace().geometry.location.F);
scope.marker.setPosition(location);
scope.map.setCenter(location);
scope.map.setZoom(16);
});
});
}
};
});
.directive('myModal', function () {
return {
templateUrl: 'modal.html',
restrict: 'E',
replace: true,
scope: true,
controller: function ($scope) {
},
link: function postLink(scope, element, attrs) {
scope.$watch(attrs.visible, function(value) {
if(value == true) {
$(element).modal('show');
}
else {
$(element).modal('hide');
}
});
$(element).on('shown.bs.modal', function(){
scope.$apply(function(){
scope.$parent[attrs.visible] = true;
});
});
$(element).on('hidden.bs.modal', function(event){
scope.$apply(function(){
scope.$parent[attrs.visible] = false;
});
});
}
};
});
When the user write his address, and hit Enter, the listener on the map, find the address and marker on the map.
I did like that because it was the best solution I found for my project.
I hope that helps.
PS: Sorry my english :/

Angular Factory data isn't shared correctly

I'm trying to share some data from the controller in the current view to my navigation bar. but the data is shared wrong, or not synced correctly.
this is my factory:
myApp.factory('HeaderData', function () {
var data = {
Visible: true,
PageTitle: ''
};
return {
getVisible: function () {
return data.Visible;
},
setVisible: function (visible) {
data.Visible = visible;
console.log("HeaderData: " +visible);
},
getPageTitle: function () {
return data.PageTitle;
},
setPageTitle: function (title) {
data.PageTitle = title;
}
};
});
then in my controllers I'm doing the following:
myApp.controller('homeCtrl',function ($scope, HeaderData) {
HeaderData.setVisible(false);
console.log("HomeCtrl: " + HeaderData.getVisible());
});
in the Nav controller I read the data in like following:
myApp.controller('navCtrl', function ($scope, HeaderData) {
console.log("NavCtrl: " +HeaderData.getVisible());
$scope.showHeader = HeaderData.getVisible();
$scope.pageTitle = HeaderData.getPageTitle();
});
the following output is logged:
NavCtrl: true
HeaderData: false
HomeCtrl: false
So my NavContrl is loaded before my Data is set, and this is logical because it's like this in the HTML:
<div ng-controller="navCtrl">
<ng-include ng-show="showHeader" src="'../partials/common/header.html'"></ng-include>
</div>
<div ng-view></div>
So how can I make it work that my navCtrl updates the data correctly, and in this example hide the header when the $scope.showHeader is set to false?
Instead of assigning a primitive to $scope, assign an object to scope so that you can bind by reference. By binding by reference, you ensure that scope properties resolve to the same reference.
When you bind to a primitive (string, int, etc), it creates a copy of the original value on scope as soon as it is assigned. Now you have multiple copies of the variable on different scopes, and they all behave independently of each other.
myApp.factory('HeaderData', function() {
var data = {
Visible: true,
PageTitle: ''
};
return {
...
getData = function() {
return data;
}
};
});
And assign the model to scope:
myApp.controller('navCtrl', function($scope, HeaderData) {
$scope.data = HeaderData.getData();
});
And in your HTML:
<div ng-controller="navCtrl">
<div ng-show="data.Visible">HEADER</div>
</div>

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