Can’t get ‘comment’ value from camForm - angularjs

I want to get ‘refusalComment’ from my form (when i write some value into it ) but i can’t make this operation every time i deploy project i got this error:
ReferenceError: variableValue is not defined
at Array.eval (eval at (camunda-tasklist-ui.js?bust=7.8.0:5), :27:84)
here is my code example:
<form role=“form”>
var selectedDocuments=$scope.selectedDocuments=[];
var variableManager=camForm.variableManager;
var json=$scope.json={
id:1,
cardNumber:“12345678”,
organizationNameGE:“ptp”,
organizationNameEN:“psp”
};
$scope.selectedDocuments.push($scope.json);
camForm.on('form-loaded', function() {
// declare a 'json' variable 'customer'
camForm.variableManager.createVariable({
name: 'selectedDocuments',
type: 'String',
value: $scope.selectedDocuments
});
});
var comments = $scope.comments=[];
comments.length =$scope.selectedDocuments.length ;
camForm.on('variables-fetched', function() {
// value has been fetched, bind to $scope.user
$scope.refusalComment = $( '#refusalComment', camForm.formElement).textContent(variableValue);
console.log( $scope.refusalComment+"see comment");
$scope.selectedDocuments=EnrichValue(variableManager.variable('selectedDocuments').value,$scope.refusalComment);
});
camForm.on('submit', function(evt) {
// set value in variable manager so that it can be sent to backend
variableManager.variableValue('selectedDocuments', $scope.selectedDocuments);
});
function EnrichValue(data,comment){
for(var i=0;i<Object.keys(json).length;i++){
json[i].comment=comment;
comments[i]=comment;
}
return json;
}
what should i change to make to get rid of this error?

Related

Backbone error: Model is not a constructor

Afternoon all, I'm relatively new to backbone and have been stumped for 3 days with this error which I have not seen before.
I have a collection 'TestCollection' which defines it's model as a function. When the collection is loaded I get an error the first time it attempts to make a model with class 'TestModel'.
The error I get is:
Uncaught TypeError: TestModel is not a constructor
at new model (testCollection.js:14)
at child._prepareModel (backbone.js:913)
at child.set (backbone.js:700)
at child.add (backbone.js:632)
at child.reset (backbone.js:764)
at Object.options.success (backbone.js:860)
at fire (jquery.js:3143)
at Object.fireWith [as resolveWith] (jquery.js:3255)
at done (jquery.js:9309)
at XMLHttpRequest.callback (jquery.js:9713)
I believe I have given both the collection and the model all of the code they should need to work. It feels like something has gone wrong with the loading, but when I put a console.log at the top of the model file I could see that it is definitely being loaded before the collection attempts to use it.
Any help would be massively appreciated.
TestCollection:
define([
'backbone',
'models/testModel'
], function(Backbone, TestModel) {
var TestCollection = Backbone.Collection.extend({
model: function(attrs) {
switch (attrs._type) {
case 'test':
console.log('making a test model')
return new TestModel();
}
},
initialize : function(models, options){
this.url = options.url;
this._type = options._type;
this.fetch({reset:true});
}
});
return TestCollection;
});
TestModel:
require([
'./testParentModel'
], function(TestParentModel) {
var TestModel = TestParentModel.extend({
urlRoot: 'root/url',
initialize: function() {
console.log('making test model')
}
});
return TestModel;
});
File where TestCollection is made:
define(function(require) {
var MyProjectCollection = require('collections/myProjectCollection');
var TestCollection = require('collections/testCollection');
Origin.on('router:dashboard', function(location, subLocation, action) {
Origin.on('dashboard:loaded', function (options) {
switch (options.type) {
case 'all':
var myProjectCollection = new MyProjectCollection;
myProjectCollection.fetch({
success: function() {
myProjectCollection.each(function(project) {
this.project[project.id] = {};
this.project[project.id].testObjects = new TestCollection([], {
url: 'url/' + project.id,
_type: 'test'
});
});
}
});
}
});
});
I've had a look around stack overflow, it does not appear to be the issue below (which seems to be the most common issue).
Model is not a constructor-Backbone
I also do not think I have any circular dependencies.
Any help would be massively appreciated as I am completely stumped. I've tried to include only the relevant code, please let me know if additional code would be useful.
Thanks
I can't say for other parts of the code but an obvious problem you have is misunderstanding what data is passed to the model creator function.
var TestCollection = Backbone.Collection.extend({
model: function(attrs) {
switch (attrs._type) { // attrs._type does exist here
console.log( attrs ); // Will print { foo: 'bar' }
case 'test': // This will always be false since attrs._type does not exist
console.log('making a test model')
return new TestModel();
default:
return new Backbone.Model(); // Or return some other model instance,
// you MUST have this function return
// some kind of a Backbone.Model
}
},
initialize : function(models, options){
this.url = options.url;
this._type = options._type;
this.fetch({reset:true});
}
});
new TestCollection([ { foo: 'bar' }], {
url: 'url/' + project.id,
_type: 'test' // This will NOT be passed to the model attrs, these are
// options used for creating the Collection instance.
})
To re-iterate. When you instantiate a Collection you pass an array of plain objects [{ foo: 'bar'}, { foo: 'baz'}] ( or you get them via fetch like you're doing ). That object will be passed as the attrs parameter in the model function, and the model function MUST return at least some kind of a Backbone.Model instance so you need a fallback for your switch statement.

Testing Angular-Resource: Expected an Object, got a Resource

When trying to test some simple angular code using $resource, I end up with a Resource object which contains a $promise key and hence a failure of the form: Failure/Error: Expected Resource(...) to equal Object(...)
I was expecting to get back the object I passed to the respond method as part of httpBackend.expectGET('/books/5.json').respond(my_book). Am I using $resource wrong or is something wrong in my test?
Code
var bookApp = angular.module('bookApp',
[
'ngResource',
]
);
function BookController(scope, $resource) {
var ctrl = this;
var Book = $resource('/books/:selected.json', {selected:'#id'});
ctrl.fetch_book = function(id){
console.log('Selecting options ' + id);
Book.get({selected:id}, function(data){
console.log('Received: ' + JSON.stringify(data));
ctrl.current_book = data;
});
};
}
BookController.$inject = ['$scope', '$resource'];
bookApp.component('book', {
controller: BookController
});
Test
describe('component: tree', function() {
var component_controller, $componentController, httpBackend, my_book;
beforeEach(module('bookApp'));
beforeEach(inject(function($httpBackend, _$componentController_) {
httpBackend = $httpBackend;
$componentController = _$componentController_;
}));
describe('$ctrl.fetch_book(book_id)', function(){
beforeEach(function() {
component_controller = $componentController('book');
my_book = {title: 'Sanctuary', id: '5'};
});
it('fetches the book with id=book_id', function(){
httpBackend.expectGET('/books/5.json').respond(my_book);
component_controller.fetch_book(5);
httpBackend.flush();
console.log('Options: ' + JSON.stringify(component_controller.current_book));
console.log('constructor: ' + JSON.stringify(component_controller.current_book.constructor.name));
expect(component_controller.current_book).toEqual(my_book);
});
});
});
Result
$ bundle exec teaspoon -f documentation
component: tree
$ctrl.fetch_book(book_id)
fetches the book with id=book_id (FAILED - 1)
# Selecting options 5
# Received: {"title":"Sanctuary","id":"5"}
# Options: {"title":"Sanctuary","id":"5"}
# constructor: "Resource"
Failures:
1) component: tree $ctrl.fetch_book(book_id) fetches the book with id=book_id
Failure/Error: Expected Resource({ title: 'Sanctuary', id: '5',
$promise: Promise({ $$state: Object({ status: 1, value:
<circular reference: Object> }) }), $resolved: true }) to equal
Object({ title: 'Sanctuary', id: '5' }).
Finished in 0.02600 seconds
1 example, 1 failure
Try this in your tester:
expect(component_controller.current_book).toEqual(angular.toJSON(my_book));
It'll strip the object's properties and you'll have a match.
You can also try angular.equals but I haven't tested that.
Try adding the following to your spec file and see if it works. I saw it in the PhoneCat example and it worked for me.
beforeEach(function() {
jasmine.addCustomEqualityTester(angular.equals);
});
You can try doing something like this:
expect(component_controller.current_book.toJSON()).toEqual(my_book);
I had the same issue where I got an error of
Expected object to be a kind of Object, but was Resource(
This is what I had before:
expect(self.project).toEqual(mockProject);
And after I added .toJSON() it was all good:
expect(self.project.toJSON()).toEqual(mockProject);
Hope this helps!

Can I change variables of pre defined constants in angularJs?

I defined a constant 'ngGPlacesDefaults' which sets default values of 'google place search' config file. But now I want to change the values of defaults dynamically i.e types:['airport'], types['backery'] etc as needed. And for this I injected the above constant inside my controller and tried to set defaults from inside my controller. But it's not working I mean It's not changing the values.
I am providing code for config file, constant and controller.
Any help would be much appreciated!!
map config code->
app.config(function(ngGPlacesAPIProvider, ngGPlacesDefaults){
ngGPlacesAPIProvider.setDefaults(ngGPlacesDefaults);
});
app.constant code->
app.constant('ngGPlacesDefaults', {
radius:1000000,
types:['shoe_store'],
nearbySearchKeys: ['name','geometry', 'reference'],
placeDetailsKeys: ['name','formatted_address', 'formatted_phone_number',
'reference', 'website', 'geometry', 'email']
});
controller code ->
app.controller('scdfindCustomerCtrl',function($scope,ngGPlacesAPI,$http,ngGPlacesDefaults){
ngGPlacesDefaults.types = ["electronics_store"];
$scope.getDetails = function(ref){
$scope.details = ngGPlacesAPI.placeDetails({reference:ref}).then(
function (data) {
$scope.det=data;
console.log(data);
return data;
});
}
$scope.positions = [{lat:37.7699298,lng:-122.4469157}];
$scope.addMarker = function(event) {
var ll = event.latLng;
$scope.positions.push({lat:ll.lat(), lng: ll.lng()});
$scope.data = ngGPlacesAPI.nearbySearch({latitude:ll.lat(), longitude:ll.lng()}).then(
function(data){
$scope.person=data;
console.log(data);
return data;
});
}
....some more code...
});
In current scenario I want this code to show the list of 'electronics_store' but It's showing list of 'shoe_store'.

WebSQL data into AngularJs DropDown

I have very simple question about getting data from WebSql
I have DropDown i.e
<select id="selectCatagoryFood" data-role="listview" data-native-menu="true"
ng-init="foodCatagory = foodCatagories.cast[0]"
ng-options="foodCatagory as foodCatagory.text for foodCatagory in foodCatagories.cast"
ng-model="foodCatagory"
ng-change="changeFoodCatagory()">
</select>
now i want to add data init from webSQL. I already get Data from webSql but i am confuse that how to add that data into DropDown
An example or hints maybe very helpful for me.
Update 1 :: Add Controller Code
myApp.controller('foodSelection',function($scope,foodCatagories){
$scope.foodCatagories = foodCatagories;
$scope.changeFoodCatagory = function(){
alert($scope.foodCatagory.value);
}
});
Update 2 webSQL and JayData
_context.onReady({
success: showData,
error: function (error){
console.log(error);
}
});
function showData(){
var option = '';
_context.FoodGroup.forEach(function(FG)
{
option += '<option value="'+FG.FoodGroupID+'">'+FG.Description+'</option>';
}).then(function(){
console.log(option);
});
}
Update 3
var myApp = angular.module('myApp',[]);
myApp.factory('foodCatagories',function(){
var foodCatagories = {};
foodCatagories.cast = [
{
value: "000",
text: "Select Any"
}
];
return foodCatagories;
});
Update 4
One thing that i didn't mention is that I am using JayData for getting data from webSQL to my App
I will try to explain how it works:
EDIT: Live demo
html
Here is your stripped down select.
<select ng-options="item as item.text for item in foodCategories"
ng-model="foodCategory"
ng-required="true"
ng-change="changeFoodCategory()">
</select>
The directive ng-options will fill automatically the option elements in your select. It will take the foodCategories variable from the $scope of your controller and foreach item in the collection, it will use the text property as the label shown (<option>{{item.text}}</option>') and it will select the whole objectitemas the value of the selectedoption. You could also refer to a property as the value like ({{item.text}}). Then yourng-modelwould be set to theid` value of the selected option.
The directive ng-model corresponds to the variable in the $scope of your controller that will hold the value of the selected option.
The directive ng-required allows you to check if a value has been selected. If you are using a form, you can check if the field is valid formName.ngModelName.$valid. See the docs for more details on form validation.
The directive ng-change allows you to execute a function whenever the selected option changes. You may want to pass the ng-model variable to this function as a parameter or call the variable through the $scope inside the controller.
If no default value is set, angular will add an empty option which will be removed when an option is selected.
You did use the ng-init directive to select the first option, but know that you could set the ng-model variable in your controller to the default value you would like or none.
js
Here I tried to simulate your database service by returning a promise in the case that you are doing an async request. I used the $q service to create a promise and $timeout to fake a call to the database.
myApp.factory('DbFoodCategories', function($q, $timeout) {
var foodCategories = [
{ id: 1, text: "Veggies", value: 100 },
{ id: 2, text: "Fruits", value: 50 },
{ id: 3, text: "Pasta", value: 200 },
{ id: 4, text: "Cereals", value: 250 },
{ id: 5, text: "Milk", value: 150 }
];
return {
get: function() {
var deferred = $q.defer();
// Your call to the database in place of the $timeout
$timeout(function() {
var chance = Math.random() > 0.25;
if (chance) {
// if the call is successfull, return data to controller
deferred.resolve(foodCategories);
}
else {
// if the call failed, return an error message
deferred.reject("Error");
}
}, 500);
/* // your code
_context.onReady({
success: function() {
deferred.resolve(_contect.FoodGroup);
},
error: function (error){
deferred.reject("Error");
}
});
*/
// return a promise that we will send a result soon back to the controller, but not now
return deferred.promise;
},
insert: function(item) {
/* ... */
},
update: function(item) {
/* ... */
},
remove: function(item) {
/* ... */
}
};
});
In your controller you set the variables that will be used in your view. So you can call your DbFoodCategories service to load the data into $scope.foodCategories, and set a default value in $scope.foodCategory that will be used to set the selected option.
myApp.controller('FoodSelection',function($scope, DbFoodCategories){
DbFoodCategories.get().then(
// the callback if the request was successfull
function (response) {
$scope.foodCategories = response; //response is the data we sent from the service
},
// the callback if an error occured
function (response) {
// response is the error message we set in the service
// do something like display the message
}
);
// $scope.foodCategory = defaultValue;
$scope.changeFoodCategory = function() {
alert($scope.foodCatagory.value);
}
});
I hope that this helped you understand more in detail what is happening!
See this example and how use $apply to update the data in scope.
in the new version we released a new module to support AngularJS. We've started to document how to use it, you can find the first blogpost here
With this you should be able to create your dropdown easily, no need to create the options manually. Something like this should do the trick:
myApp.controller('foodSelection',function($scope, $data) {
$scope.foodCatagories = [];
...
_context.onReady()
.then(function() {
$scope.foodCatagories = _context.FoodGroup.toLiveArray();
});
});
provided that FoodGroup has the right fields, of course

Setting urlRoot from inside of model: backbone

I have written the following code:
var Parent = Backbone.Model.extend({
initialize: function() {
console.log("this is parent's init function");
},
defaults: {
name: "",
id: 0
},
parentFetch: function() {
this.set("urlRoot", "/cgi-bin/yoman.pl");
console.log("debug output" + this.urlRoot + ":" + this.get("urlRoot"));
this.fetch({
arg: "her",
success: function() {
console.log("fetch success");
},
error: function() {
console.log("fetch error");
}
});
},
urlRoot: "/cgi-bin/hello1.pl"
});
$(document).ready(function() {
console.log("this is ready function");
var myParent = new Parent();
myParent.parentFetch();
});
Here I am trying to implement parentFetch function, in which I am setting this.urlRoot variable of the model. However, by some reason, the fetch uses old value of urlRoot, which was set at defaults.
Why does this.set("urlRoot", ...) doesn't change it's value?
Also I have printed to console the output:
console.log("debug output" + this.urlRoot + ":" + this.get("urlRoot"));
the output shows:
debug output/cgi-bin/hello1.pl:/cgi-bin/yoman.pl
What is a problem here and how to fix it?
set() is used to set attributes of the model, like name, etc. urlRoot is not an attribute so set() can't be used to set it.
To set it, simply assign it like other object values, ie:
this.urlRoot = "/cgi-bin/yoman.pl";
instead of
this.set("urlRoot", "/cgi-bin/yoman.pl");
For reference, if you were to try this.get('urlRoot') or this.attributes.urlRoot in the model in your example you will find that they both return "/cgi-bin/yoman.pl" because of the set() call you made.

Resources