please find my controller file..
(function () {
var app = angular.module('myApp',['formly','formlyBootstrap'])
app.run(function(formlyConfig) {
formlyConfig.setType({
name: 'custom',
templateUrl: 'custom.html'
});
});
app.factory('jsonService', function jsonService($http){
return {
getJSON: getJSON
};
function getJSON(abc) {
console.log("Inside" + abc);
return $http.get('readJson.php?abc='+abc);
}
});
app.controller('MyController', function ($scope) {
$scope.user = {};
$scope.fillSecDropDown = [];
$scope.userFields = [{
"key": "hobbies",
"type": "select",
"templateOptions": {
"label": "Hobbies",
"options":[{id:'A',title:'A'},{id:'B',title:'B'}],
"valueProp": "id",
"labelProp":"title",
onChange: function (abc) {
selectHobbies(abc);
}
}
}]
})
})();
selecthobbies.js file.
function selectHobbies(abc)
{
console.log("here " + abc);
$scope.fillDropDown = [ // getting error here //
{
key: 'custom',
type: 'custom',
templateOptions:{
options: [],
valueProp: 'id',
labelProp: 'title'
},
controller:function($scope) {
console.log("here");
});
}
}
];
}
I am unable to access $scope in my selecthobbies.js file.
is there any way i can call onChange function which is not in a same file..???
I am getting the error $scope is not defined..
index.html file
<html>
<head>
<script src="api-check.js"></script>
<script src="angular.js"></script>
<script src="formly.js"></script>
<script src="jquery.min.js"></script>
<script src="angular-formly-templates-bootstrap.js"></script>
<script src="mycontroller.js"></script>
<script src="selecthobbies.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
</head>
<body ng-app="myApp" ng-controller="MyController">
<formly-form model="user" fields="userFields"></formly-form>
<formly-form model="fillSecDropDown" fields="fillDropDown"></formly-form>
</body>
</html>
Since you asked for an external file, you can change your function like this :
function selectHobbies(scope, abc)
{
console.log("here " + abc);
scope.fillDropDown = [ // getting error here //
{
key: 'custom',
type: 'custom',
templateOptions:{
options: [],
valueProp: 'id',
labelProp: 'title'
},
controller:function($scope) {
console.log("here");
});
}
}
];
return scope;
}
and in your controller :
app.controller('MyController', function ($scope) {
$scope.user = {};
$scope.fillSecDropDown = [];
$scope.userFields = [{
"key": "hobbies",
"type": "select",
"templateOptions": {
"label": "Hobbies",
"options":[{id:'A',title:'A'},{id:'B',title:'B'}],
"valueProp": "id",
"labelProp":"title",
onChange: function (abc) {
$scope = selectHobbies($scope, abc);
}
}
}]
})
but that is not pretty at all, just don't do that if you can.
If you need this, then something is wrong with your function, please just refactor it in a better way.
EDIT -> You can do it with a service, in a much better way :
(function() {
'use strict';
angular
.module('yourApp')
.factory('yourService', yourServiceFactory);
function yourServiceFactory() {
var service = {
get: get
}
return service;
function get(abc) {
return {
key: 'custom',
type: 'custom',
templateOptions:{
options: [],
valueProp: 'id',
labelProp: 'title'
},
controller:function($scope) {
console.log("here");
});
}
}
}
})();
And then in your controller :
app.controller('MyController', function ($scope, yourService) {
$scope.user = {};
$scope.fillSecDropDown = [];
$scope.userFields = [{
"key": "hobbies",
"type": "select",
"templateOptions": {
"label": "Hobbies",
"options":[{id:'A',title:'A'},{id:'B',title:'B'}],
"valueProp": "id",
"labelProp":"title",
onChange: function (abc) {
$scope.fillSecDropDown.push(yourService.get(abc));
}
}
}]
})
Move your selecthobbies.js file. into your controller, would be something like this:
(function () {
var app = angular.module('myApp',['formly','formlyBootstrap'])
app.run(function(formlyConfig) {
formlyConfig.setType({
name: 'custom',
templateUrl: 'custom.html'
});
});
app.factory('jsonService', function jsonService($http){
return {
getJSON: getJSON
};
function getJSON(abc) {
console.log("Inside" + abc);
return $http.get('readJson.php?abc='+abc);
}
});
app.controller('MyController', function ($scope) {
$scope.user = {};
$scope.fillSecDropDown = [];
$scope.userFields = [{
"key": "hobbies",
"type": "select",
"templateOptions": {
"label": "Hobbies",
"options":[{id:'A',title:'A'},{id:'B',title:'B'}],
"valueProp": "id",
"labelProp":"title",
onChange: function (abc) {
selectHobbies(abc);
}
}
}];
$scope.selectHobbies = function(abc){
console.log("here " + abc);
$scope.fillDropDown = [ // getting error here //
{
key: 'custom',
type: 'custom',
templateOptions:{
options: [],
valueProp: 'id',
labelProp: 'title'
},
controller:function($scope) {
console.log("here");
});
}
}
];
}
})
})();
Related
I have this code:
(function () {
"use strict";
angular.module("workPlan").controller("workPlanListController", ["workPlans",
"clients",
"inspectionAuthority",
"$http",
"config",
"workPlanServise",
workPlanListController]);
function workPlanListController(workPlans,
clients,
inspectionAuthority,
workPlanServise,
config,
$http) {
var self = this;
this.workPlanList = workPlans;
this.lookups = {
client: clients,
authority: inspectionAuthority
};
this.gridOptions = {
expandableRowTemplate: 'app/workPlan/templates/expandableRowTemplate.tmpl.html',
expandableRowHeight: 150,
enableColumnMenus: false,
enableSorting: true,
enableFiltering: false,
enableToopTip: true,
enableHorizontalScrollbar: 0,
onRegisterApi: function (gridApi) {
gridApi.expandable.on.rowExpandedStateChanged(null, function (row) {
if (row.isExpanded) {
row.entity.subGridOptions = {
columnDefs: [{ name: 'Authority', field: 'authName', cellTooltip: true },
{ name: '# Items, field: 'items2inspect', cellTooltip: true },
{ name: '% Inspected, field: 'percentage', cellTooltip: true }]
};
$http.get(config.baseUrl + "api/workPlan/").success(function (result) {
row.entity.subGridOptions.data = result.data;
});
}
});
}
}
this.gridOptions.columnDefs = [
{ name: 'client, field: 'clientName', cellTooltip: true, headerTooltip: true },
{ name: 'sites', field: 'siteNumbers', cellTooltip: true, headerTooltip: true },
{ name: 'checkedSites', field: 'siteNumbersInspected', cellTooltip: true, headerTooltip: true }];
this.gridOptions.data = self.workPlanList;
}
})();
When I try expand row I get on this row:
$http.get
Error : $http.get in not a function.
Any idea why I get error?
You shouldn't change the dependency sequence while using dependencies in the controller function.
Code
angular.module("workPlan").controller("workPlanListController", ["workPlans",
"clients",
"inspectionAuthority",
"$http",
"config",
"workPlanServise",
workPlanListController
]);
function workPlanListController(workPlans,
clients,
inspectionAuthority,
$http, //<-- $http should be here, instead of placing it at the end.
config,
workPlanServise
) {
Same SO Answer here
I have a complex object and I'm trying to set the
SelectedTransportation
property which I manually add in a mapping. The code properly populates the dropdownlist, but I can't figure out how to set SelectedTransportation properly. I've tried setting it during the mapping process and after mapping through a loop but all attempts have failed. Seems like this should be rather easy, but the solution eludes me.
var model = {"LoadCarriers":[
{
"Id":1,
"IsDispatched":false,
"IsPrimary":false,
"RCNotes":null,
"CarrierId":4,
"Carrier":{
"Id":4,
"Name":"West Chase",
"MCNumber":"EPZEPFEEGJAJ",
"DOTNumber":"AJSCEXFTFJ",
"InternetTruckStopCACCI":"DJOGRBQ",
"Phone":"0773283820",
"RemitToPhone":null,
"AlternatePhone":"4428290470",
"Fax":null,
"MainAddress":{
"ShortAddress":"Toledo, IN",
"Address1":"Lee St",
"Address2":"apt 131",
"City":"Toledo",
"State":"IN",
"PostalCode":"07950",
"Country":"US"
},
"RemitToAddress":{
"ShortAddress":"Fuquay Varina, MO",
"Address1":"Manchester Rd",
"Address2":"",
"City":"Fuquay Varina",
"State":"MO",
"PostalCode":"23343",
"Country":"US"
},
"EmailAddress":"jason.price14#gmail.com",
"Coverage":null,
"CanLoad":false,
"InsuranceNumber":"RIQERAIAJBMP",
"InsuranceExpirationDate":"\/Date(1442978115587)\/",
"AdditionalInsurance":null,
"ProNumber":"07643",
"URL":"http://www.west-chase.com",
"AccountId":1
},
"Dispatcher":"Bob McGill",
"DriverId":null,
"LoadDriver":{
"Id":1,
"Name":"Bobby Pittman",
"Phone":"8950121068",
"Mobile":null,
"MT":false,
"Tractor":"OQRNBP",
"Trailer":"QTZP",
"Location":"Lee St",
"TansportationSize":"958424896573544192",
"Pallets":null,
"IsDispatched":false,
"TransportationId":7,
"Transportation":{
"Name":"Flatbed or Van",
"Id":7
},
"TransportationList":[
{
"Name":"Flat",
"Id":1
},
{
"Name":"Van or Reefer",
"Id":2
},
{
"Name":"Rail",
"Id":3
},
{
"Name":"Auto",
"Id":4
},
{
"Name":"Double Drop",
"Id":5
},
{
"Name":"Flat with Tarps,",
"Id":6
},
{
"Name":"Flatbed or Van",
"Id":7
},
{
"Name":"Flatbed, Van or Reefer",
"Id":8
},
{
"Name":"Flatbed with Sides",
"Id":9
},
{
"Name":"Hopper Bottom",
"Id":10
},
{
"Name":"Hot Shot",
"Id":11
},
{
"Name":"Lowboy",
"Id":12
},
{
"Name":"Maxi",
"Id":13
},
{
"Name":"Power Only",
"Id":14
},
{
"Name":"Reefer w/ Pallet Exchange",
"Id":15
},
{
"Name":"Removable Gooseneck",
"Id":16
},
{
"Name":"Step Deck",
"Id":17
},
{
"Name":"Tanker",
"Id":18
},
{
"Name":"Curtain Van",
"Id":19
},
{
"Name":"Flatbed Hazardous",
"Id":20
},
{
"Name":"Reefer Hazardous",
"Id":21
},
{
"Name":"Van Hazardous",
"Id":22
},
{
"Name":"Vented Van",
"Id":23
},
{
"Name":"Van w/ Pallet Exchange",
"Id":24
},
{
"Name":"B-Train",
"Id":25
},
{
"Name":"Container",
"Id":26
},
{
"Name":"Double Flat",
"Id":27
},
{
"Name":"Flatbed or Stepdeck",
"Id":28
},
{
"Name":"Air",
"Id":29
},
{
"Name":"Ocean",
"Id":30
},
{
"Name":"Walking Floor",
"Id":31
},
{
"Name":"Landoll Flatbed",
"Id":32
},
{
"Name":"Conestoga",
"Id":33
},
{
"Name":"Load Out",
"Id":34
},
{
"Name":"Van Air-Ride",
"Id":35
},
{
"Name":"Container Hazardous",
"Id":36
}
],
"CarrierId":0,
"Carrier":null
},
"Carriers":null,
"LoadId":1
}
]};
var loadDriverModel = function (data) {
ko.mapping.fromJS(data, {}, this);
this.SelectedTransportation = ko.observable();
};
var loadDriverMapping = {
'LoadDriver': {
key: function (data) {
return data.Id;
},
create: function (options) {
return new loadDriverModel(options.data);
}
}
};
var carrierModel = function (data) {
ko.mapping.fromJS(data, loadDriverMapping, this);
};
var carrierMapping = {
'LoadCarriers': {
key: function (data) {
return data.Id;
},
create: function (options) {
return new carrierModel(options.data);
}
}
};
var model = ko.mapping.fromJS(model);
ko.applyBindings(model);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.js"></script>
<!-- ko foreach: LoadCarriers -->
<select class="form-control" data-bind="options:LoadDriver.TransportationList, optionsText:'Name', value:$data.LoadDriver.SelectedTransportation"></select>
<!-- /ko -->
#JasonlPrice I can't test right now, but I suggest you to not use this in loadDriverModel function.
Try create a variable and return that variable.
Something like this:
var loadDriverModel = function (data) {
var viewModel = ko.mapping.fromJS(data);
viewModel.SelectedTransportation = ko.observable();
return viewModel;
};
I ended up replacing this
var loadDriverModel = function (data) {
ko.mapping.fromJS(data, {}, this);
this.SelectedTransportation = ko.observable();}
with the following.
var loadDriverModel = function (data) {
var self = this;
ko.mapping.fromJS(data, {}, this);
this.SelectedTransportation = ko.computed(function () {
return ko.utils.arrayFirst(self.TransportationList(), function (item) { return item.Id() === self.TransportationId() });
}, self);
};
Now it works properly. Computed Observables were the solution.
I have:
{
headerTemplate: 'Email invoices',
field: 'email_invoices',
filterable: {
ui: gridFunctions.yesNoFilterUI.bind(activeGrid),
extra: false
}
},
The filter UI is defined with:
define(['jquery', 'kendo', 'util/addMenu', 'config'], function ($, kendo, addMenu, config) {
var obj = {
...
yesNoFilterUI: function (e) {
var that = this;
e.kendoDropDownList({
dataSource: [
{
"id": "1",
"text": "Yes"
},
{
"id": "0",
"text": "No"
}
],
optionLabel: "Select yes/no",
dataTextField: "text",
dataValueField: "id",
change: function (e) {
obj.setInternalFilter(that, 'yesNo', 'eq', this.value());
}
});
},
...
}
return obj;
})
The column filter 'yesNo' is wrong, this needs to be a variable containing the field name i.e. email_invoices.
How can I get or pass this in along the lines of:
obj.setInternalFilter(that, field, 'eq', this.value());
?
I have a jquery DataTable as
html page
<div id="content">
</div>
js code
(function ($) {
'use strict';
var module = {
addTable: function () {
var output = '<table id="table1"></table>';
$('#content').append('<p></p>' + output);
var data = [];
data = this.getData();
$('#table1').dataTable({
"data": data,
"columns": [
{
"title": 'Name',
mDataProp: 'name',
width: '20%'
},
{
"title": 'Company',
mDataProp: 'company'
},
{
"title": 'Salary',
mDataProp: 'salary'
}],
'scrollY': '400px',
'scrollCollapse': false,
'paging': false
});
},
getData: function () {
var arr = [];
for (var i = 0; i < 100; i++) {
var obj = {
name: 'John',
company: 'XYZ',
salary: '$XYZ'
};
arr.push(obj);
}
return arr;
}
};
$(document).ready(function () {
$('#content').append('Loading....');
module.addTable();
});
})(jQuery);
On initial load, it shows an empty table. Data comes after performing some search. How to show the data by default on initial load?
This is due to javascripts asynchronicity. getData() is not finished at the time of the dataTable initialization. You could make some refactoring, so getData invokes addTable as a callback instead.
var module = {
addTable: function (data) {
var output = '<table id="table1"></table>';
$('#content').append('<p></p>' + output);
$('#table1').dataTable({
"data": data,
"columns": [
{
"title": 'Name',
mDataProp: 'name',
width: '20%'
},
{
"title": 'Company',
mDataProp: 'company'
},
{
"title": 'Salary',
mDataProp: 'salary'
}],
'scrollY': '400px',
'scrollCollapse': false,
'paging': false
});
},
getData: function (callback) {
var arr = [];
for (var i = 0; i < 100; i++) {
var obj = {
name: 'John',
company: 'XYZ',
salary: '$XYZ'
};
arr.push(obj);
}
return callback(arr);
},
init : function() {
this.getData(this.addTable);
}
};
...
module.init();
init() calls getData(callback) with addTable as param, addTable have had the param data added.
demo -> http://jsfiddle.net/bLzaepok/
I assume your getData code is only per example, and you are using AJAX (or whatever) IRL. Call the callback in the callback :
getData: function (callback) {
$.ajax({
...
success : function(data) {
callback(data);
}
});
}
I am trying to write unit tests for a controller that gets a promise from a service, but in Jasmine I am getting:
TypeError: Cannot read property 'then' of undefined
In controller I call .then() on returned promise from service.
Can anybody help please? I am surely missing something obvious.
Here is a plunk: http://plnkr.co/edit/vJOopys7pWTrTQ2vLgXS?p=preview
'use strict';
describe('Language controller', function() {
var scope, translationService, createController;
beforeEach(function() {
var mockTranslationService = {};
module('dictApp', function($provide) {
$provide.value('translationService', mockTranslationService);
});
inject(function($q) {
mockTranslationService.languages = [
{
name: 'slovak'
},
{
name: 'czech'
}
];
mockTranslationService.languagesWithWords = [{
name: 'slovak',
words: [{
key: 'Car',
translation: 'Auto',
createdOn: 0
}, {
key: 'Flower',
translation: 'Kvet',
createdOn: 0
}]
}, {
name: 'czech',
words: {
key: 'Plaza',
translation: 'Namesti',
createdOn: 0
}
}];
mockTranslationService.getLanguages = function() {
var deferred = $q.defer();
deferred.resolve(this.languages);
return deferred.promise;
};
});
});
beforeEach(inject(function($controller, $rootScope, _translationService_) {
scope = $rootScope.$new();
translationService = _translationService_;
createController = function () {
return $controller('LanguageCtrl',
{$scope: scope, translationService: translationService});
};
scope.$digest();
}));
it('should get the language array', function() {
spyOn(translationService, 'getLanguages');
createController();
expect(translationService.getLanguages).toHaveBeenCalled();
});
});
and this is the controller:
dictControllers.controller('LanguageCtrl', ['$scope', 'translationService', function($scope, translationService){
$scope.getLanguages = function() {
translationService.getLanguages().then(function(){
$scope.languages = translationService.languages;
});
};
$scope.getLanguages();
$scope.getWords = function(language) {
translationService.getWords(language);
};
$scope.newWord = {};
$scope.addWord = function(language) {
translationService.addWord($scope.newWord, language);
$scope.newWord = {};
};
}]);
Use spyOn(mockTranslationService, 'getLanguages').and.returnValue(deferred.promise); instead. It also makes more sense to resolve the promise after the getLocations() has been called rather than before getLocations() returns the promise. You should also check the languages.
inject(function($q) {
deferred = $q.defer();
mockTranslationService.languages = [
{
name: 'slovak'
},
{
name: 'czech'
}
];
mockTranslationService.languagesWithWords = [{
name: 'slovak',
words: [{
key: 'Car',
translation: 'Auto',
createdOn: 0
}, {
key: 'Flower',
translation: 'Kvet',
createdOn: 0
}]
}, {
name: 'czech',
words: {
key: 'Plaza',
translation: 'Namesti',
createdOn: 0
}
}];
mockTranslationService.getLanguages = function () {
};
spyOn(mockTranslationService, 'getLanguages').and.returnValue(deferred.promise);
});
it('should get the language array', function() {
createController();
deferred.resolve();
scope.$digest();
expect(translationService.getLanguages).toHaveBeenCalled();
expect(scope.languages).toEqual(translationService.languages);
});
Plunkr