How to access an attribute in a template, besides by its name? - backbone.js

In an underscore template, is there any other way to access an attribute besides by its name? I've got one called "2a" and I cannot reference it directly, due to its first character being a number. For example, this doesn't work:
<input type="checkbox" name="6a" <%= 6a ? "checked" : "" %>>
Thanks!

You have a few options other than renaming the offending attribute.
Underscore's _.template has a variable option:
By default, template places the values from your data in the local scope via the with statement. However, you can specify a single variable name with the variable setting.
So you could do this:
<input type="checkbox" name="6a" <%= v['6a'] ? "checked" : "" %>>
and this:
var t = _.template($('#whatever').html(), null, { variable: 'v' });
var h = t({ '6a': true });​
Demo: http://jsfiddle.net/ambiguous/hBhfu/
You could also wrap it manually when you call the template function:
t({ v: { '6a': true }});
You'd use the same template as above in this case.
Demo: http://jsfiddle.net/ambiguous/8AZKw/

Related

call a value in AngularJS

I want to call a particular value in my app through AngularJS
here is my controller(js file)
//infocomnamebyid
$http.get('/csuv5.asmx/infocomname', {
params: {
id: $scope.additionalinfoparam.Id
}
})
.then(function (response) {
{
$scope.comnamebyinfo = response.data.info;
console.log(response.data.info);
}
});
}
the value is printing in console like this
[Object]
0
:
Object
comname
:
"QED Productions Pvt Ltd"
__proto__
:
Object
length
:
1
__proto__
:
Array[0]
but now I want to print the same on my label
<label></label>
Try JSON.parse()
$scope.comnamebyinfo = JSON.parse(response.data.info);
and in HTML,
<label ng-model="comnamebyinfo"></label>
Give your label a model:
<label ng-model='aName'></label>
Then you can assign a value to it in your controller:
$scope.aName = response.data.info;
There would be no reason to use two-way binding for a label. This means, instead of using the ng-model, you could:
1) String interpolation:
<label> {{ comnamebyinfo }}</label>
or 2) The ng-bind directive:
<label ng-bind="comnamebyinfo"></label>
More information about the differences between those options can be found here.

How to bind a list of checkboxes in AngularJS

I have a list of checkboxes as following :
<div flex="50" ng-repeat="formationType in formationTypeList">
<md-checkbox class="md-warn md-align-top-left"
value="{{formationType.codeFormation}}"
name="formationSelection[]"
ng-checked="formationSelection.indexOf(formationType) > -1"
ng-click="toggleFormationTypeSelection(formationType)">
{{ formationType.nom }}
</md-checkbox>
</div>
This is the format of formationSelection after I send my form :
formationSelection = [
{
codeFormation: 1,
nom: "ENSA"
},
{
codeFormation: 2,
nom: "CPGE"
}
]
In another scenario I want when I open my form to check the checkboxes which are defined in an array as following :
$scope.formationSelection = res.candidatureProjetProfessionnel.formations;
the object res.candidatureProjetProfessionnel.formations contains this :
formationSelection = [
{
codeFormation: 1,
nom: "ENSA"
},
{
codeFormation: 2,
nom: "CPGE"
}
]
And when I inspect $scope.formationSelection it contains the data I got from res.candidatureProjetProfessionnel.formations :
But I don't know why my checkboxes are not checked even though the $scope.formationSelection is not empty.
How can I solve this ?
i'm not sure what the md-checkbox directive is so i'm just going to use a normal checkbox input. Generally speaking, setting a default value for inputs in angular involves 2 things:
Make sure your inputs have ng-model to store the value of the checkbox and for 2 way data binding (so that you can set it from the controller as well)
In your controller set the variable declared in the ng-model to whatever default value you want.
So in you html:
<input type="checkbox" class="md-warn md-align-top-left" ng-
model="formationSelection[$index]" ng-true-value="{{formationType}}"
name="formationSelection[]">
Make sure you use ng-true-value to declare the value of each checkbox when checked. The ng-model is set to formationSelection[$index] which basically means each checkbox is an item inside the formationSelection array, this way the array will be the collection of the values of all checked inputs.
Now $scope.formationSelection = res.candidatureProjetProfessionnel.formations should work
Here's a working plunker:
http://plnkr.co/edit/sGm39DRWH9EOReiiSrIl?p=preview
You have to use ng-model as shown below.It should be an object like $scope.data = {};.This is just an example where hope you can get the point and work on your scenario. Actually you're having individual check boxes as shown below but values are being set through the loop.So you can apply this concept for your use case as well.Hope this will help to you.
Html
<md-checkbox ng-model="data.cb1" aria-label="Checkbox 1">
Checkbox 1: {{ data.cb1 }}
</md-checkbox>
JS
$scope.data = {};
$scope.data.cb1 = true;
Play with it on Codepen
I think that your method isFormation(formationType) on the directive ng-checked it's not return the result.
In your controller create a function
$scope.isFormation(_type){
return $scope.formationSelection.filter(function(f){return f.nom === _type;}).length > 0;
}

Difficulty adding multiple classes wit ng-class

I'm trying to add two classes to this div using ng-class, but even though checkForActive is returning true, it's being ignored and only class_{{$index}} is getting added.
If I remove class_{{$index}} altogether, active is added correctly.
Is there an obvious mistake in my syntax here?
<div "ng-class="{active: checkForActive, disabled: checkForDisable, class_{{$index}}} "></div>
You could just provide true value to the key class_{{$index}} just to that property gets added as a class name to the class list of the element. It is just the way you do active: checkForActive.
i.e
{active: checkForActive, disabled: checkForDisable, class_{{$index}} :true}
But i believe there could be some undesired behavior due the usage of interpolation ({{) within the ng-class directive (Atleast used to happen with older versions). So you could as well use an array.
ng-class="[checkForActive && 'active' , checkForDisable && 'disabled', 'class_' + $index]"
The above method will add a class name false if active or disabled is false, which should be harmless.
Or pass index to a controller function say getStatus($index) and return the object from there and use it in the ng-Class directive.
$scope.getClass = function(){
var obj = {active: $scope.checkForActive, disabled: $scope.checkForDisable};
obj['class_' + this.$index] = true;
return obj;
}
and
ng-class="getClass()"
#Okazari pointed out that it indeed works by mixing class with ng-class so you could also do:
class="class_{{$index}}" ng-class="{active: checkForActive, disabled: checkForDisable}"

How to set ime-mode in element input angular?

I read at http://docs.angularjs.org/api/ng.directive:input
<input
ng-model="{string}"
[name="{string}"]
[required]
[ng-required="{boolean}"]
[ng-minlength="{number}"]
[ng-maxlength="{number}"]
[ng-pattern="{string}"]
[ng-change="{string}"]>
</input>
How can I set ime-mode in this code ?
You are able to add another attributes to input (it won't cause any errors), so simply add, for example, style="ime-mode: disabled" (or add class attribute and set ime-mode in your css - it's better way in my opinion)
ime-mode is not supported in Chrome, Safari, or Opera. Read more about ime-mode and its compatibility here: https://developer.mozilla.org/en-US/docs/Web/CSS/ime-mode
If you do want to use it in supported versions of IE and Firefox, here are two methods:
Use a class:
<input class="ime">
CSS:
.ime {
ime-mode: disables;
}
Inline style (not recommended):
Also note that in your markup is not valid. input tags are self closing and do not need </input>. Also, with angular, you probably don't need the name and required attributes. You markup should probably look like this:
<input
ng-model="myModel"
ng-required="required"
ng-minlength="minLength"
ng-maxlength="maxLength"
ng-pattern="regex"
ng-change="myChangeFunction()"
>
to data-bind in these values with Angular:
app.controller('myCtrl', function($scope) {
$scope.myModel = 'input value here';
$scope.required = true;
$scope.minLength = 5;
$scope.maxLength = 20;
$scope.regex = '/put your regex here/';
$scope.myChangeFunction() {
//code to run when value of input is changed
};
});

how to set the default 'select' ng-model to an object?

I am trying to do a search engine interface with angular. The user selects some parameters in a form, click "search" and then it fills the url with the parameters using $location.search()
the search interface parameters which are used to build the form :
params = {
milestones: [ "a", "b", "c", "d", etc. ],
properties: [
{ "name": "name A", type: "text" },
{ "name": "name B", type: "checkbox" },
{ etc. }
]
}
inside the controller :
$scope.query = $location.search(); // get the parameters from the url
$scope.search = function (query) { // set the parameters to the url
$location.search(query);
};
and the html of the form
<select ng-model="query.milestone_name" ng-options="ms for ms in params.milestones">
<option value="">-select milestone-</option>
</select>
<select ng-model="property" ng-options="prop.name for prop in params.properties" ng-change="query.property_name=property.name">
<!-- if the object 'property' was passed in the url, it would look like this `%5Bobject%20Object%5D`, so its 'name' parameter is converted to a string -->
<option value="">-select property-</option>
</select>
<span ng-switch="property.type">
<label ng-switch-when="text">{{query.property_name}}: <input type="text" ng-model="query.property_value"></label>
<label ng-switch-when="checkbox">{{query.property_name}}: <input type="checkbox" ng-model="query.property_value"></label>
</span>
<button ng-click="search(query)">search</button>
and somewhere else in the page is the list of results.
the user can also access to a search result page with an url like this:
http://myapp.com/search?milestone_name=a&property_name=name%20A
almost everything works fine : the list of results is displayed, the "milestone" parameter is pre-selected with the correct value in the select component, but not the "property" parameter because it's not a string, it's an object.
how can i set the default value (ng-model) of the select component to an object ?
or any other idea on how i should do this ?
When using an array of objects for the select to iterate over, the ng-options directive needs to have an attribute of the object to match against (and differentiate between arrays)
Use the track by section of the directive declaration eg
<select ng-model="property" ng-options="prop.name for prop in params.properties track by prop.name" ng-change="query.property_name=property.name">
<!-- if the object 'property' was passed in the url, it would look like this `%5Bobject%20Object%5D`, so its 'name' parameter is converted to a string -->
<option value="">-select property-</option>
</select>
You can use this form of comprehension expression in ngOptions: label group by group for value in array. Html drop down list will display only name of selected object. Model will contain whole selected object. You can set selected object from controller.
<select ng-model="property"
ng-options="prop as prop.name for prop in params.properties">
</select>
Check this plnkr example.
ng-options is generating some options to be used with ng-model. In your syntax (prop.name for prop in params.properties) you've told it to bind to the object found in the array (as oppose to a property on it - which is what you want to do) and use its name property as the value to display. So when you try and set the ng-model to be an object that's not in the ng-options array nothing happens - I'm guessing because it's using reference/shallow equality and not deep equality. So what you should do is either:
Convert the ng-options object to be an array of strings.
Use a syntax that involves keys, such as:
prop.name as prop.name for prop in params.properties
http://jsfiddle.net/C5ENK/
If that doesn't suit your needs let me know why and I'll see if I can help further.
i found a kind of solution…
when selecting a property, it saves the index of this object and then when the page loads, it sets the ng-model of the select to the value of this index. it uses this : example for setting the index and this example for getting the value of this index in the array of objects.

Resources