How to obtain selected value from angucomplete-alt? - angularjs-directive

I am trying to use Angucomplete-alt -
autocomplete directive for AngularJS without any luck.
Problem is: selected value from autocomplete list does not update my model.
In Angular application
var app = angular.module("workScheme2App", ['angucomplete-alt']);
workScheme2App.controller('SMSController', function ($scope, $http) {
this.anketa =
{
DeliveryAddress_Province: {
id: 0,
name: ""
}
};
};
In view:
<angucomplete-alt id="DeliveryAddress_Province" name="DeliveryAddress_Province"
pause="400"
selectedObject="anketa.DeliveryAddress_Province"
remote-url="../../Client/getListProvince?query="
title-field="name"
/>
remote-url="../../Client/getListProvince?query="
MVC controller method in "remote-url" attribute successfully returns JSON array of objects like this:
[{id: 1, name: "Киевская"}, {id:2, name: "Одесская"}]
Dropdown appears and I can select needed value, but after selection exception happened:
Error: [$compile:nonassign] Expression 'undefined' used with directive 'angucompleteAlt' is non-assignable!
http://errors.angularjs.org/1.3.11/$compile/nonassign?p0=undefined&p1=angucompleteAlt
at REGEX_STRING_REGEXP (angular.js:63)
at $get.parentSet (angular.js:7658)
at parentValueWatch (angular.js:7671)
at Object.regularInterceptedExpression (angular.js:12838)
at Scope.$get.Scope.$digest (angular.js:14222)
at Scope.$get.Scope.$apply (angular.js:14493)
at HTMLDivElement. (angular.js:21427)
at HTMLDivElement.p.event.dispatch (jquery.js:2)
at HTMLDivElement.p.event.add.g.handle.h (jquery.js:2)
I cant figure out how to assign selected to anketa.DeliveryAddress_Province object ? Can anyone help please?

The problem was in attribute "selectedObject", after i change it to "selected-object" it works properly. Hyphenated attributes transforms in directive to camelCase properties.

Related

Bootstrap Tokenfield show empty tags list. Laravel App

I have a problem with autocomplete.
Firslty I get an array with tags:
var tagsList = #json(\App\Helpers\Clients::getTags());
And then:
$('#tags').tokenfield({
beautify:false,
autocomplete: {
source: [tagsList],
delay: 100
},
showAutocompleteOnFocus: true
});
This code works correctly. No errors in console. But show the list of tags empty!
If I change tagList by static list, work correctly:
$('#tokenfield').tokenfield({
autocomplete: {
source: ['red','blue','green','yellow','violet'],
delay: 100
},
showAutocompleteOnFocus: true
});
Console debug show the list correctly:
But in app only show this (repeat, no errors console):
Looks like css doesnt work but every css is linked correctly.
Any idea what is happenning?¿
console.log(tagsList) throw:
Best regards.
tokenfields source attribute needs an array, but you are passing an object to it.
The problem is that you do not have a sequential array so #json cannot convert it to an array but instead converts it to an object.
Solution 1
Convert the output from \App\Helpers\Clients::getTags() to a sequential array.
Solution 2
get the object values in JS and pass it to source
$('#tags').tokenfield({
beautify:false,
autocomplete: {
source: Object.values(tagsList),
delay: 100
},
showAutocompleteOnFocus: true
});
#Joaquin
How about you only use array to your source property?
$('#tokenfield').tokenfield({
autocomplete: {
source: Object.values(taglist),
delay: 100
},
showAutocompleteOnFocus: true
});

Backbone model .toJSON() doesn't work after .fetch()

Good day! I need to render a model's attributes to JSON so I can pass them into a template.
Model:
var UserInfo = Backbone.Model.extend({
url: appConfig.baseURL + "users/",
});
Template:
<script type="text/html" class="template" id="profile-form">
<h2 class="ui-li-heading"><%= username %></h2>
<p class="ui-li-desc"><strong><%= phone %></strong></p>
</script>
View:
var ProfilePageView = Backbone.View.extend({
events: {
'click #edit': "edit"
},
initialize: function () {
this.template = $.tpl['profile-form'];
var user = new UserInfo()
user.fetch({
data: $.param({email: localStorage.getItem('user_email')}),
type: 'POST'
});
console.log(user) //returns correct object with attrs
console.log(user.toJSON()) //returns empty object
},
render: function (eventName) {
$(this.el).html(this.template());
},
edit: function () {
window.workspace.navigate('#account/edit', { trigger: true});
}
});
When i put in console something like this, user.toJSON() returns correct data
var user = new UserInfo();
user.fetch({
data: $.param({email: localStorage.getItem('user_email')}),
type: 'POST'
});
But when i put it to my view, its returns Object {}.
Where is a mistake or tell me how can differently pass to the template data received from the server in json format? Thanks!
You appear to have two problems. fetch is asyncronous, so you need to use a callback to use the information. But first, an explanation about toJSON. .toJSON() doesn't actually return a JSON string, it returns an object that is what you want JSON to stringify. This allows you to modify the toJSON method to customize what attributes will be taken from your model or collection and added to the JSON string representation of your model. Here is a quotation from the Backbone.js docs:
toJSON collection.toJSON([options])
Return a shallow copy of the model's attributes for JSON
stringification. This can be used for persistence, serialization, or
for augmentation before being sent to the server. The name of this
method is a bit confusing, as it doesn't actually return a JSON string
— but I'm afraid that it's the way that the JavaScript API for
JSON.stringify works.
So you should replace this line in your code
console.log(user.toJSON())
with this one
console.log(JSON.stringify(user))
The object that you saw was returned by toJSON will then be turned into JSON.
Now, even after you do that, it won't work properly, because you will execute the console.log before you get the data for your model from fetch. fetch is asynchronous, so you need to call any code you want to be executed after the fetch is done in the success callback:
user.fetch({
data: $.param({email: localStorage.getItem('user_email')}),
type: 'POST',
success: function(){
console.log(user);
console.log(JSON.stringify(user));
}
});

SAP UI5 - How to pass values for a controller?

I want to pass values from a view to controller on button press.In view am passing productJson which is an object.But i am unable to retrieve that value in controller.Please help.
View js:
new sap.m.Button({
text: "Add to Cart",
press:[oController.addtoCartBtnPress,oController,productJson],
})
Controller js:
addtoCartBtnPress:function(e,oView,productJson)
{
}
Result:
oView and productJson values are returned as undefined.
The data should be first value in the press array. Per the sdk docs for sap.m.Button:
press : fnListenerFunction or [fnListenerFunction, oListenerObject] or
[oData, fnListenerFunction, oListenerObject]
The listener function should then have 2 arguments: 1-the event; and 2- the data.
onPressFn: function(evt, data) { ... }
To get the view, just use:
var view = this.getView();
"this" will be equal to whatever you pass as the third value in the press array, and should usually be the controller in order to match the behaviour of xml/html views.
And an alternative to passing the data in the press call would be to use the view-model binding, especially if you are already using that model binding elsewhere in the view. But it depends how many products you have and other factors so I won't assume it will be ideal for your case.
//in the view
var productModel = new sap.ui.model.json.JSONModel(productJson);
view.setModel(productModel, "product");
//in the controller:
var data = view.getModel("product").getData();

Filter JSON data based on current URL route

The problem
I'm trying to filter json data and display only a portion of it on an Angular page, based on the page's current URL.
In detail
I have a list of 100 JSON objects, and each one looks like this:
{
"name": "Evangeline Perreault",
"age_1": 1,
"total_age": 1,
"photo_small": "img/400/001_400.jpg",
"photo_medium": "img/800/001_800.jpg",
"photo_large": "img/1200/001_1200.jpg",
"photo_extralarge": "img/1600/001_1600.jpg",
"video": 67443664,
"id": 1,
"quote": "test quote here and here",
"type": 1
},
The 'type' attribute is what I want to use to filter out the subsets of my data. With that in mind, I tried to setup my URL structure to tie the type attribute here to my url. Here is my route:
angular.module('100_Ages', ['mydirectives', 'ngResponsiveImages']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/100_Ages/nav/:personType', {templateUrl: 'partials/person-list.html', controller: NavListCtrl}).
otherwise({redirectTo: '/100_Ages'});
}]);
So, I have pointed the route to the 'type' field in my JSON and I tried writing a controller to tie the two together.
function NavListCtrl($scope, $routeParams, $http) {
$http.get('person.json').success(function(data) {
angular.forEach(data, function(person) {
if (person.type == $routeParams.personType)
$scope.person = person;
});
});
}
And here is my partial template:
<div class="nav_outer"><img class="nav_img" ng-src="{{person.photo_small}}" ng-alt="{{person.name}}" /></div>
I expected this to display all the matching images for the URL type I'm on. So, if I'm on "/100_Ages/nav/3", I expected all the images (roughly 10 pictures) from the objects with a type of "3" to display. However, it only displayed the last object with a type of "3".
So, I tried an ng-repeat like so:
<div class="nav_outer" ng-repeat="person in persons"><img class="nav_img" ng-src="{{person.photo_small}}" ng-alt="{{person.name}}" /></div>
I expected that to loop through and show all the matching images, but that made nothing at all show up.
I think my problem has to do with the angular.forEach, but I'm not sure how else to tie my JSON type to the page's typeid.
Thanks for any suggestions.
The ng-repeat should work if you push each item into an array. (Also, you are referring to a 'persons' object in the ng-repeat, which doesn't exist according to code provided). So, try this:
$http.get('person.json').success(function(data) {
$scope.persons = [];
angular.forEach(data, function(person) {
if (person.type == $routeParams.personType)
$scope.persons.push(person);
// or alternatively - this.push(person), with the optional 3rd param of $scope.persons (I don't really understand that, but whatever...)
});
});
Now with the array populated, your ng-repeat="person in persons" should work.
UPDATE:
If the success object was already an array of objects, then just set the scope object to the array - no need to iterate through them:
$http.get('person.json').success(function(data) {
$scope.persons = data;
})

asp.net mvc 3 ViewModel collection property to json not working

Good evening everyone. I am currently using MVC 3 and I have a viewmodel that contains a property that is a List. I am currently using json2's JSON.stringify method to pass my viewmodel to my action method. While debugging I am noticing that all the simple properties are coming thru but the collection property is empty even though I know for sure that there is at least one object in the collection. I wanted to know if there is anyone that is running into the same issue. Below is the code that I am using to post to the action method:
$.post("/ReservationWizard/AddVehicleToReservation/",
JSON.stringify('#ViewData["modelAsJSON"]'),
function (data) {
if (data != null) {
$("#vehicle-selection-container").html(data);
$(".reservation-wizard-step").fadeIn();
}
});
The object #ViewData["modelAsJSON"] contains the following json and is passed to my action method
{"NumberOfVehicles":1,"VehiclesToService":[{"VehicleMakeId":0,"VehicleModelId":0}]}
As you can see the property "VehiclesToService" has one object but when it gets to my action method it is not translated to the corresponding object in the collection, but rather the collection is empty.
If anyone has any insight into this issue it would be greatly appreciated.
Thanks in advance.
UPDATE
OK after making the recommended changes and making the call to new JavaScriptSerializer().Serialize(#Model) this is the string that ultimately gets sent to my action method through the post
'{"NumberOfVehicles":1,"VehiclesToService":[{"VehicleMakeId":0,"VehicleModelId":0}]}'
I can debug and see the object that gets sent to my action method, but again the collection property is empty and I know that for sure there is at least one object in the collection.
The AddVehicleToReservation action method is declared as follows:
public ActionResult AddVehicleToReservation(VehicleSelection selections)
{
...
return PartialView("viewName", model);
}
Here's the problem:
JSON.stringify('#ViewData["modelAsJSON"]')
JSON.stringify is a client side function and you are passing as argument a list that's stored in the ViewData so I suppose that it ends up calling the .ToString() and you have
JSON.stringify('System.Collections.Generic.List<Foo>')
in your final HTML which obviously doesn't make much sense. Also don't forget that in order to pass parameters to the server using the $.post function the second parameter needs to be a javascript object which is not what JSON.stringify does (it generates a string). So you need to end up with HTML like this:
$.post(
'ReservationWizard/AddVehicleToReservation',
[ { id: 1, title: 'title 1' }, { id: 2, title: 'title 2' } ],
function (data) {
if (data != null) {
$('#vehicle-selection-container').html(data);
$('.reservation-wizard-step').fadeIn();
}
}
);
So to make this work you will first need to serialize this ViewData into JSON. You could use the JavaScriptSerializer class for this:
#{
var myList = new JavaScriptSerializer().Serialize(ViewData["modelAsJSON"]);
}
$.post(
'#Url.Action("AddVehicleToReservation", "ReservationWizard")',
// Don't use JSON.stringify: that makes JSON request and without
// proper content type header your sever won't be able to bind it
#myList,
function (data) {
if (data != null) {
$('#vehicle-selection-container').html(data);
$('.reservation-wizard-step').fadeIn();
}
}
);
And please don't use this ViewData. Make your views strongly typed and use view models.