Add default class and class from scope in angular? - angularjs

I want to add two classes in angular. One is always the same and one is retrieved by the scope.
I attempted this:
<label class="checkbox" ng-switch-when="checkbox" ng-class="{{field.name}}">
<input
name="{{field.key}}"
type="checkbox"
value="Option 1"
ng-model="$storage[field.key]"
>
{{field.label}}
</label>
It generated two-class attributes in the DOM.
This:
<label ng-switch-when="checkbox" ng-class="{{field.name}} checkbox">
<input
name="{{field.key}}"
type="checkbox"
value="Option 1"
ng-model="$storage[field.key]"
>
{{field.label}}
</label>
didn't add anything to the class-attribute at all

I put together a simple example on plunker for you here (http://plnkr.co/edit/H7JstMuvHSlwPSy3raPO?p=preview). The core of the example is:
<div ng-class="{red: showRed, bold: showBold}">Hello Plunker!</div>
To make this example work, you need to define two booleans "showRed" and "showBold" in your controller. Its very simple but the controller code looks like:
var app = angular.module("App", []);
app.controller("ctrl", function($scope){
$scope.showRed = true;
$scope.showBold = true;
});
When you toggle these boolean values true/false, the classes will toggle on and off the element. In order to make this easy to see, I added two buttons to the example so you can toggle without changing code. Hope this helps you out. Best of luck!

ng-class expects an expression that evaluates to a string, an array or a map. Btw. You don't need {{ because the whole string already is an expression.
Your second expression cannot be evaluated. It's like a line in JavaScript field.name checkbox - that's not valid code. field.name + ' checkbox' would be. You could use that.
An array would definitely be easier to use if you had more dynamic classes:
[field.name, someOtherVariable, 'checkbox'].

Related

angular 2 - checkbox "checked" depend on function not on property biind

I have a checkbox that needs to be shown as selected depending on a function result instead of binding it to an object property.
This would be easy, but is not possible:
<input type="checkbox" ([ngModel])="category.selected">
And this does not work, as even checked="false" results in a checkbox being displshownayed as selected:
<input type="checkbox" [attr.checked]="isCategorySelected(category.id)"/>
I need an outcome like this
<input type="checkbox">
<input type="checkbox" checked>
depending on the result isCategorySelected(id).
Any help is appreciated.
You cannot use [(ngModel)] in this scenario because it defines a 2-way databind, and you are passing a function.
Instead, you could simple use [ngModel], like the snippet below. This syntax defines a one-way databind.
<input type="checkbox" [ngModel]="yourBooleanFunction()"/>
You can read more about ngModel here.
Let me know if you have any other problem with it.

How to programmatically uncheck checkbox?

I want to programmatically uncheck a checkbox. I know how to it in javascript but since I'm using angular, i think it's different.
Here's the link of jsfiddle : https://jsfiddle.net/TKVH6/499/
This is the first time I used jsfiddle so please let me know if you cant see the script and html.
This is the html
<input type="checkbox" ng-model="v" ng-click="checkAll()" />
<button ng-click="x()">eto</button>
This is the angular
$scope.x = function () {
$scope.v.checked=false;
};
I know there are lots of question like this, I've already tried those but I can't make it work.
Thanks!
<input type="checkbox" ng-checked="v" ng-click="checkAll()" />
In your controller
$scope.v = true; // or false
First thing : You have specified controller on ul and bind click event of button outside the ul so moved ng-controller on div.
Second thing: In order to check it pragmatically you need to set $scope.Items[i].Selected = true;
$scope.x = function () {
alert("x");
$scope.Items[0].Selected=true;
};
Why we need to set Selected property of Items[i] while I have not declared?
The reason behind that is your html binding is something like this:
<li ng-repeat="item in Items">
<label>{{item.Name}}
<input type="checkbox" ng-model="item.Selected" />
</label>
</li>
Here every item is element from Items array that means your checkbox checked value is now bind to selected property of that object. Even though you have not defined that property in Items collection angular will create it and will bind it to that property. So you are required to set that property. I hope it would help you.
Here is working fiddle => link

How do I add a class to a div if the item in ng-repeat is not valid?

I am trying to use $invalid to add a class to a div when the input within the div is not filled out. However I just cannot work out the syntax.
<div ng-app ng-controller="miniC">
<form name="persondetails" novalidate>
<div ng-repeat="account in myAccounts" ng-class="{'has-error': account.amount.$invalid}" >
<input name="{{account.name}}" ng-model="account.amount" required="required"/>
</div>
</form>
</div>
function Account(nameArg, amountArg){
this.name = nameArg;
this.amount = amountArg;
}
The surrounding div needs to have class="has-error" when the inner item is not filled in. I have done similar on single bound elements just cant seem to get this working....
$invalid flag is not attached to the ngModel, but to the form controller (ngFormController).
In your example you're not demonstrating that you're even using ngForm, and you should, if you want angular to validate your form.
Next, you're trying to dynamically set the input's name attribute. ngForm won't like it because ngFormControll will be initialized before your expression is evaluated.
Workaround is to wrap each ng-repeat iteration inside new ngForm (ngForm can be nested and it will just work) and name your inputs with some static string value (e.g. name="amount").
So, you'll want your view written as:
<div
ng-repeat="account in myAccounts"
ng-class="{'has-error': form.amount.$invalid}"
ng-form="form"
>
<input name="amount" ng-model="account.amount" required="required"/>
</div>

How to pass custom directive name dynamically in class attribute of div tag?

I am very new to AngularJS. I have made a custom directive user and I want to call it dynamically in class attribute by using a variable.
e.g. $scope.dirName = "user";
When i use this variable in below code:
<div class = {{dirName}}></div>
Its result must show two input fields with specified values. But it is not doing so. When I replace {{dirName}} with user. It is working fine, means two input fields are shown with values as specified. Can anybody tell, what mistake I am doing?
This is index.html
<div ng-controller = "Ctrl">
<form name = "myForm">
<div class = {{dirName}}></div>
<hr>
<tt>userName : {{user}}</tt>
</form>
This is script.js
<pre>var app = angular.module('App',[]);
app.controller('Ctrl', function($scope){
$scope.user = {name:'adya',last:'Rajput'};
$scope.dirName = "user";
});
app.directive('user',function(){
return{
restrict:'C',
templateUrl:'template.html'
};
});</pre>
template.html contains:
UserName : <input type='text' name='userName' ng-model='user.name' required>
LastName : <input type='text' name='lastName' ng-model='user.last'>
Unfortunately, you cannot save names of directives in string variables and access them in the HTML. You can, however, save a string in a variable in $scope and use ng-switch to select the correct directive:
<div ng-switch="dirName">
<div ng-switch-when="ng-user">
<div ng-user></div>
</div>
<div ng-switch-when="...">
...
</div>
</div>
However, now it might be better to use something more descriptive than ng-user to switch over.
Sidenote: Do not use ng- prefix in your own directives. Angular uses that prefix so that it does not collide with other namespaces. You should use your own prefix for your directives.
Update: For the updated question as to why <div class="{{dirName}}"></div> does not work, it happens because angular $compiles the directive only once. If you first $interpolate the content of the template (which will replace {{dirName}} with ng-user) and then explicitly $compile it before entering it in the HTML, it should work.

AngularJS - Model not updating on selection of radio button generated by ng-repeat

I am generating a bunch of radio buttons using ng-repeat, and then trying to update a model when one of them is selected. This doesn't appear to be working.
The same markup works just fine when the radio inputs are hardcoded as opposed to being generated by ng-repeat.
This works:
<input type="radio" ng-model="lunch" value="chicken" name="lunch">
<input type="radio" ng-model="lunch" value="beef" name="lunch">
<input type="radio" ng-model="lunch" value="fish" name="lunch">
{{lunch}}
This doesn't:
<input type="radio" ng-model="lunch" ng-repeat="m in meat" value="m" name="lunch">
{{lunch}}
See jsfiddle showing both here: http://jsfiddle.net/mark_up/A2qCS/1/
Any help would be appreciated.
Thanks
<div ng-controller="DynamicCtrl">
<input type="radio" ng-model="$parent.lunch" ng-repeat="m in meat"
ng-value="m" name="lunch">
{{lunch}}
</div>
Should do the trick.
As I understand it, ng-repeat creates its own $scope. so you need to refer to the $parent $scope; Yes, AngularJS is tricky. Also you need to change the value to ng-value too.
the above issue was discussed here
That happens because ng-repeat creates a new scope. Basically, each <input> is creating a selectedOption value on its own inner scope. To work around that, create a new container object for that value. For example, you could declare in your controller:
$scope.data = {selectedOption: x};
And then in your template, use ng-model="data.selectedOption"
in this way, ng-model gets updated .. :)
this is tricky
Just need to replace value with ng-value

Resources