I have what I think is the correct accessor syntax for binding my UI-Grid control, I don't get any errors or any data. I just get a warning about Mutating the prototype.
My json data structure is like this:
{
"records": [
{
"acctIdInfo": {
"acctId": "257905480",
"acctCode": "ABC10101102",
"acctName": "BIG CORPORATION",
"acctRole": [
"C"
]
},
"acctNameAddr": {
"addressLine": [
"7280 JAMISON ST"
],
"cityName": "VANCOUVER",
"stateCd": "US-WA",
"countryCd": "US",
"postalCd": "97979"
}
}
]
}
The code in my AngularJS controller to bind is:
var app = angular.module('app', ['ui.grid', 'ngResource'])
.factory('jsonDataFactory', function ($resource) {
return {
custData: $resource('data.json', {}, {
query: {method: 'GET', params: {}, isArray: false}
}),
};
});
app.controller('MainCtrl', ['$scope','$resource','jsonDataFactory', function ($scope,$resource, jsonDataFactory) {
$scope.gridOptions = {
enableRowSelection: true,
enableSelectAll: true,
selectionRowHeaderWidth: 35
};
$scope.gridOptions.columnDefs = [
{ name: 'acctIdInfo.acctId' },
{ name: 'acctIdInfo.acctCode'},
{ name: 'acctIdInfo.acctName'},
{ name: 'acctNameAddr.addressLine' }
];
$scope.gridOptions.data = jsonDataFactory.custData.query().records;
$scope.CustomerData = [];
$scope.CustomerData = jsonDataFactory.custData.query();
console.log($scope.CustomerData);
$scope.gridOptions.data = $scope.CustomerData.records;
}]);
Here is my plnk of what I tried -
I think I'm close...
Do assign a data to ui-grid data source once ajax call response comes back. I assumed that you had used $resource, so you can have promise over it to attach callback function.
jsonDataFactory.custData.query().$promise.then(function(response){
$scope.CustomerData = response;
console.log($scope.CustomerData);
$scope.gridOptions.data = $scope.CustomerData.records;
});
Related
Could you please help me to write down the Jasmine(2.0) test code for mock of the service in a Controller as below.
readJsonFactory.js
angular.module('myAssignmentTaskApp')
.factory('readJsonFactory', function ($http) {
var userExists = false;
var responseData = [];
return $http.get('../json/AutoTestDB1.json').then(function (response) {
for (var i=0; i<response.data.StatusTable.length; i++){
responseData.push(response.data.StatusTable[i].RunId);
}
return response;
}).catch(function (error) {
//
})
});
The Controller file readjson.js is as below.
angular.module('myAssignmentTaskApp')
.controller('ReadjsonctrlCtrl', function ($scope,readJsonFactory,$location) {
var testCaseNameFromReadJsonFactory = [];
readJsonFactory.then(function (response) {
for (`var i=0;i<response.data.StatusTable.length;i++`){
testCaseNameFromReadJsonFactory.push(response.data.StatusTable[i].TestScenario);
}
}
})
AutoTestDB1.json
{
"StatusTable": [
{
"RunId": "bah_regression_alternateFlights",
"TestScenario": "BAH - Change Default Search Options",
"Area": "Yes",
"TestCases": [
{
"TestID": "",
"TestName": "VerifyCarDepotPageIsDisplayed_Test",
"Status": [
{
"Release": " R301",
"Runner": "yes",
"Status": "Passed",
"details": [
{
"ResponseTime": "1m 26s 702ms",
"Status": "Passed",
"RecordData": 1511519114413
}
]
}
]
}
]
}
]
}
Please post an apporopriate spac.js file.
Thanks in advance.
You do use the following to mock your service
beforeEach(function() {
angular.mock.module('myAssignmentTaskApp', ($provide) => {
const mockReadJsonFactory = {
};
$provide.constant('readJsonFactory', mockReadJsonFactory);
});
});
I'm fetching a Json with a factory "chapters", so I get the value of the property "json_file" which is another json file that I need to fetch dynamically with the factory "contents". I just need to pass the parameter "json_file" to the second factory, but I get an undefined value.
Maybe I need a service?
This is the first json file:
structure.js
[
{
"title": "Introduction",
"pages": [
{
"title": "Buongiorno",
"type" : "standard",
"json_file" : "cover_1"
},
{
"title": "Introduction",
"type" : "standard",
"json_file" : "cover_1"
}
]
},
{
"title": "Storytelling",
"pages": [
{
"title": "Italian Design & Swiss Watchmaking Expertise",
"type" : "standard",
"json_file" : "cover_1"
},
{
"title": "Interaction",
"type" : "standard",
"json_file" : "cover_1"
}
]
}
]
This is the controller.js
var bControllers = angular.module('bControllers',[]);
bControllers.controller('structureCtrl', function ($scope, $routeParams,chapters,contents){
$scope.indexChapter = 0;
$scope.indexPage = 0;
chapters.list(function(chapters) {
$scope.chapters = chapters;
$scope.pages = [];
$scope.json_file = [];
angular.forEach($scope.chapters, function(chapters,index){
angular.forEach(chapters.pages, function(page,index2){
$scope.pages.push(page);
$scope.json_file.push(page.json_file);
})
});
$scope.currentJson = $scope.chapters[$scope.indexChapter].pages[$scope.indexPage].json_file;
console.log('json-file:'+$scope.currentJson);
return $scope.currentJson;
});
contents.find($scope.currentJson, function(content) {
$scope.content = content;
});
});
And this is the factory.js
var bFactory = angular.module('bFactory',[]);
bFactory.factory('chapters', function($http){
return {
list: function (callback){
$http({
method: 'GET',
url: 'json/structure.json',
cache: true
}).success(callback);
}
}
});
bFactory.factory('contents', function($http){
return{
find:function(json_file, callback){
$http({
method: 'GET',
url: 'json/'+json_file+'.json',
cache: true
}).success(callback);
}
}
})
I was running through a set of Angular videos on YouTube and found out that .success is deprecated, and to use .then instead. I get a 404 error using both a .json file and a .txt file. I tried using .txt as people mentioned browsers don't allow local files to access other local files.
This is the $http request I have at the moment
$http.get('data/ninjas.txt').then(function(response) {
// Success!!!
$scope.ninjas = response.data;
});
This is my .json file which is valid through JSONLint
[{
"name": "Yoshi",
"belt": "green",
"rate": 50,
"available": true,
"thumb": "content/img/yoshi.png"
}, {
"name": "Crystal",
"belt": "yellow",
"rate": 30,
"available": true,
"thumb": "content/img/crystal.png"
}, {
"name": "Ryu",
"belt": "orange",
"rate": 10,
"available": true,
"thumb": "content/img/ryu.png"
}, {
"name": "Shaun",
"belt": "black",
"rate": 1000,
"available": true,
"thumb": "content/img/shaun.png"
}]
I tried testing using both httpster and using Brackets built in live preview. I get a 404 error, but the file does for sure exist as you can see in the image
If it helps, this is my whole app.js file
var myNinjaApp = angular.module('myNinjaApp', ['ngRoute']);
myNinjaApp.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/home', {
templateUrl: 'views/home.html'
})
.when('/directory', {
templateUrl: 'views/directory.html',
controller: 'NinjaController'
})
.otherwise({
redirectTo: '/home'
});
}]);
myNinjaApp.controller('NinjaController', ['$scope', '$http', function($scope, $http){
$scope.removeNinja = function(ninja){
var removedNinja = $scope.ninjas.indexOf(ninja);
$scope.ninjas.splice(removedNinja, 1)
};
$scope.addNinja = function(){
$scope.ninjas.push({
name: $scope.newninja.name,
belt: $scope.newninja.belt,
rate: parseInt($scope.newninja.rate),
available: true
});
$scope.newninja.name = "";
$scope.newninja.belt = "";
$scope.newninja.rate = "";
};
$http.get('data/ninjas.txt').then(function(response) {
// Success!!!
$scope.ninjas = response.data;
});
}]);
To make the answer complete,
Your root of your application is 'index.html', and because Angular is running within 'index.html', all files you load in your files are relative to your 'index.html'.
An example of that is seen in your route configuration, where your templates are loaded starting at 'views/*', which is a child folder of your 'index.html'
myNinjaApp.controller('NinjaController', ['$scope', '$http', function ($scope, $http) {
$http({
url: "data/ninjas.json",
method: "GET"
}).then(function (resp) {
$scope.ninjas = resp;
}, function (resp) {
// bla bla bal
});
$scope.removeNinja = function (ninja) {
var removeNinja = $scope.ninjas.indexOf(ninja);
$scope.ninjas.splice(removeNinja, 1);
}
$scope.addNinja = function () {
$scope.ninjas.push({
name: $scope.newninja.name,
belt: $scope.newninja.belt,
rate: parseInt($scope.newninja.rate),
available: true
});
$scope.newninja.name = "";
$scope.newninja.belt = "";
$scope.newninja.rate = "";
};
$scope.removeAll = function () {
$scope.ninjas = [];
};
$scope.sort = function (keyname) {
$scope.sortKey = keyname;
$scope.reverse = !$scope.reverse;
}
}]);
As for all who struggle getting not an array with net ninjas and the code above you now get the whole HTTP response under data not the JSON file itself you need to get the data property of the request so like this:
$http.get('app/Data/ninja.json').then(function(data) {
$scope.ninjas = data.data;
}, function() {
});
I am trying to write tests for angular service using jasmine and karma. I have the following code for my service call:
angular.module('omdb', [])
.factory('myservice', MyService);
MyService.$inject = ['$http'];
function MyService($http) {
var vm = this;
var service = {};
service.getData = function() {
return $http.get('omdb/mydata.json').then(function(response) {
return response.data;
});
};
return service;
};
I am tesitng it using the following file for spec as:
describe('myservice', function() {
var mockservicedata = [{
"name": "value1",
"id": "1"
}, {
"name": "value2",
"id": "2"
}, {
"name": "value3",
"id": "3"
}];
var myservice = {};
beforeEach(module('omdb'));
beforeEach(inject(function(_myservice_) {
myservice = _myservice_;
}));
it('should return search myservice data', function() {
expect(myservice.getData()).toEqual(mockservicedata);
});
});
which basically throws an error as:
Expected d({ $$state: Object({ status: 0 }) }) to equal [ Object({ name: 'value1', id: '1' }), Object({ name: 'value2', id: '2' }), Object({ name: 'value3', id: '3' }) ].
stack#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:1482:17
buildExpectationResult#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:1452:14
Env/expectationResultFactory#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:583:18
Spec.prototype.addExpectationResult#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:324:29 addExpectationResult#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:533:16
Expectation.prototype.wrapCompare/<#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:1406:7
#http://localhost:59239/movie-app/spec/omdb/myservice.spec.js:14:9
attemptSync#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:1789:9
QueueRunner.prototype.run#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:1777:9 QueueRunner.prototype.execute#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:1762:5
Env/queueRunnerFactory#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:627:7
Spec.prototype.execute#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:353:5 executeNode/<.fn#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:2360:32 attemptAsync#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:1819:9
QueueRunner.prototype.run#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:1774:9
QueueRunner.prototype.execute#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:1762:5
Env/queueRunnerFactory#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:627:7
executeNode/<.fn#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:2345:13 attemptAsync#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:1819:9
QueueRunner.prototype.run#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:1774:9
QueueRunner.prototype.execute#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:1762:5
Env/queueRunnerFactory#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:627:7
TreeProcessor/this.execute#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:2209:7
Env/this.execute#http://localhost:59239/movie-app/lib/jasmine-2.3.4/jasmine.js:678:7
window.onload#http://localhost:59239/movie-app/lib/jasmine-2.3.4/boot.js:110:5
I don't understand why it does not return data to the test. please help
Calling myservice.getData() won't actually give you the data you're expecting.
Since your getData method from MyService relies on $http's get method, you should be mocking it and then expecting that data returned.
So your test case should be like:
describe('myservice', function() {
var mockservicedata = [{
"name": "value1",
"id": "1"
}, {
"name": "value2",
"id": "2"
}, {
"name": "value3",
"id": "3"
}];
var myservice = {};
beforeEach(module('omdb'));
beforeEach(inject(function(_myservice_, _$httpBackend_) {
myservice = _myservice_;
$httpBackend = _$httpBackend_;
$httpBackend.when('GET', "omdb/mydata.json").respond({
status: 200,
data: mockservicedata
});
}));
it('should return search myservice data', function() {
var response = myservice.getData()
response.then(function(response) {
expect(response.data).toEqual(mockservicedata);
});
$httpBackend.flush();
});
});
Hope this helps.
getData() will never return data instead it will return promise object.
If you want to test it then firstly you would have to mock the data for service then you can call it and match the result in the success handler.
Code is attached below:
describe('myservice', function() {
var mockservicedata = [{
"name": "value1",
"id": "1"
}, {
"name": "value2",
"id": "2"
}, {
"name": "value3",
"id": "3"
}];
var myservice, httpBackend;
beforeEach(module('omdb'));
beforeEach(inject(function(_myservice_, $httpBackend) {
myservice = _myservice_;
httpBackend = $httpBackend;
}));
it('should return search myservice data', function() {
httpBackend.when("GET", "omdb/mydata.json").respond(mockservicedata);
var promise = myservice.getData();
promise.then(function(response) {
expect(response.data).toEqual(mockservicedata);
});
httpBackend.flush();
});
});
Please help in changing this code to be able to use $http.get html, at the moment the resulting array (html_controls) is empty. However, I can see the response in the console for all the request in $http.get. Thank you.
angular.module('exodus-grid').controller('DynamicPropertiesController', ['$scope', '$http', '$templateCache', '$q', 'coreFactory',
function($scope, $http, $templateCache, $q, coreFactory) {
//$scope.DynamicProperties = 'Property being added to the controller.';
//coreFactory.fetchData('http://uat.resources.newscdn.com.au/cs/networksales/products/latest/products.json', 'products');
// TODO: Change this harcoded value to the products.json in s3
$scope.products = [{
"id": "btyb",
"label": "BTYB + Superskin",
"description": "",
"name": "btyb",
"active": true,
"properties": [{
"bannerLink": [{
"tmp_prop_name": "bannerLink",
"label": "Header Tracking Link (Desktop)",
"type": "textbox"
}],
"superskinLink": [{
"tmp_prop_name": "superskinLink",
"label": "Sideskin Tracking Link (Desktop)",
"type": "textbox"
}],
"ImgUrl": [{
"tmp_prop_name": "ImgUrl",
"label": "Header Image Url",
"type": "textbox"
}]
}]
}, {
"id": "iframe",
"label": "iframe",
"description": "",
"name": "iframe",
"active": true,
"properties": [{
"link": [{
"tmp_prop_name": "link",
"label": "iFrame source Url",
"type": "textbox"
}]
}]
}];
var requests = [];
var html_controls = [];
var product = $scope.products[0];
var properties = angular.fromJson(product.properties);
//console.log(angular.toJson(properties));
angular.forEach(properties, function(property) {
angular.forEach(property, function(item) {
//console.log(angular.toJson(property));
if (item[0].type === "textbox") {
//console.log(angular.toJson(item));
//console.log(Object.getOwnPropertyNames(property));
//console.log(Object.keys(property));
$http.get("plugins/k-plugin-exodus-grid/templates/properties/textbox.html").success(function(html) {
html = html.replace("%%label%%", item[0].label);
html = html.replace("%%scope%%", item[0].tmp_prop_name);
//console.log(html);
html_controls.push(html);
console.log(html_controls);
var deferred = $q.defer();
requests.push(deferred.promise);
console.log(deferred, deferred)
}).then(function() {
//$scope.html = html_controls;
});
}
});
});
//console.log(html_controls);
//$scope.html = html_controls;
$q.all(requests).then(function(data) {
console.log("12312312 " , data);
$scope.html = html_controls;
});
}
]);
Looks like you are trying to resolve a array of empty promises. Since it is running async, when $q.all() us called, requests[] is still empty.
Try building an array of promises and then resolve this using q.all() instead:
var requests = []; // a list of promises
angular.forEach(properties, function(property) {
angular.forEach(property, function(item) {
var promise = $http.get("/yoururl"); // $http.get returns a promise
requests.push(promise); // add to list of requests as a promise
});
});
$q.all(requests).then(function (result) {
console.log('results' + result);
});