Button never gets un-disabled - angularjs

Second time I open this thread; had many answers on the last, but nobody gave an actual answer. My code is still not working and I'm beginning to think something very stupid is happening, or Angular is just not working properly.
This is my DOM, which I add through a directive:
<form ng-controller="controlFormulario as formCtrl">
<div style="width:50%; margin-left: 160px; margin-top: 2%">
<div class="form-group">
<label for="inputTitulo">Título</label>
<input type="titulo" class="form-control" id="inputTitulo" ng-model="formCtrl.formulario.titulo">
</div>
<div class="form-group">
<label for="inputTexto">Texto</label>
<textarea class="form-control" id="inputTexto" ng-model="formCtrl.formulario.texto"></textarea>
</div>
<div class="form-group">
<label for="fecha">Fecha</label>
<input type="fecha" class="form-control" id="fecha" ng-model="formCtrl.formulario.fecha" disabled>
</div>
<div class="form-group" >
<button ng-model="isDisabled" class="btn btn-primary" style="height:35px;width:100px;float:right;" ng-init="formCtrl.formulario.isDisabled = true" id="submit"
ng-disabled="isDisabled">
Enviar
</button>
</div>
</div>
</form>
And these are the controller and the directive:
var app = angular.module('app', []);
app.controller('controlFormulario', ['$scope', function($scope) {
var cf = this;
cf.formulario = [];
cf.formulario.fecha = new Date();
if(cf.formulario.texto != "" && cf.formulario.titulo != ""){
$scope.isDisabled = false;
} else {
$scope.isDisabled = true;
}
}]);
app.directive('formulario', [function() {
return {
restrict: 'E', // C: class, E: element, M: comments, A: attributes
templateUrl: 'modules/formulario.html',
controller: 'controlFormulario'
};
}]);
The thing I'm trying is pretty... easy? It's just getting the button active when some text is on the text and author inputs. Pretty straightforward, you know. Well, nothing is working.
Tried a normal ng-model binding to a previously written controller variable, like formCtrl.isDisabled. Didn't work.
Tried using the $scope (like now) and binding the ng-disabled attribute to the $scope.isDisabled variable. Didn't work.
Tried using a normal expression to write the "disabled" rule. Not an elegant fix, but it could work... so bad it didn't, either.
I'm getting a little frustrated to not being able to do such easy thing, so I guess I need some of your help to find out where I'm failing!

Well, you initialize $scope.isDisabled once, when the controller is instantiated, and never change it after. So, naturally, it keeps the same value forever.
Change
ng-disabled="isDisabled"
to
ng-disabled="isDisabled()"
and add the following function to the scope:
$scope.isDisabled = function() {
return cf.formulario.texto == "" || cf.formulario.titulo == "";
}
Also, note that you instantiate the controller twice for each directive instance:
once because the directive has
controller: 'controlFormulario'
and once because the template has
ng-controller="controlFormulario as formCtrl"
You should use one or the other, but not both.

Have you try to use ng-class :
<div ng-class="isDisabled ? 'class to Disabled':''">
I hope it 'll help you.

You can try this if you did not already tested :
For Dom :
<button ng-model="isDisabled" class="btn btn-primary" style="height:35px;width:100px;float:right;" ng-init="formCtrl.formulario.isDisabled = true" id="submit"
ng-disabled="FuncIsDisabled()">
And in controller you can make something like this :
function FuncIsDisabled(){
if(cf.formulario.texto != "" && cf.formulario.titulo != ""){
$scope.isDisabled = false;
} else {
$scope.isDisabled = true;
}
return $scope.isDisabled;// I'm not sure that this row is mandatory with the scope management
}

Related

Cannot read property $valid of undefined

I have a form like this -
<form name="myForm" novalidate>
There are some fields in the form which I am validating and then submitting the form like this -
<input type="button" ng-click="Save(data)" value="Save">
In the controller, I want to check if the form is not valid then Save() should show some error on the page. For that, I am setting up a watch like this -
$scope.$watch('myForm.$valid', function(validity) {
if(validity == false)
// show errors
});
But I am always getting this error on running it -
Cannot read property '$valid' of undefined
Can someone explain why?
Thanks
You just misspelled "myForm" in your controller code. In order to remove the error, Write "myform" instead of "myForm".
However I expect what you want is like this.
$scope.Save = function(data){
alert($scope.myform.$valid);
}
I setup jsfiddle.
In my case I was wrapping the form in a modal created in the controller and therefore got the same error. I fixed it with:
HTML
<form name="form.editAddress" ng-submit="save()">
<div class="form-group">
<label for="street">Street</label>
<input name="street" type="text" class="form-control" id="street" placeholder="Street..." ng-model="Address.Street" required ng-minlength="2" />
<div class="error" ng-show="form.editAddress.street.$invalid">
<!-- errors... -->
</div>
</div>
<button type="submit" class="btn btn-primary" >Save address</button>
</form>
JS
angular.module("app").controller("addressController", function ($scope, $uibModal, service) {
$scope.Address = {};
$scope.form = {};
$scope.save = function() {
if (modalInstance !== null) {
if (isValidForm()) {
modalInstance.close($scope.Address);
}
}
};
var isValidForm = function () {
return $scope.form.editAddress.$valid;
}
});

Can not get the scope variable properly

I have a simple text box and a button and whenever user click on button the alert shows the text of textbox but I want to do it this way(I know there are a lot better ways but first I want to understand why this way does not work):
var app = angular.module('app', []);
app.factory('Service', function() {
var service = {
add: add
};
return service;
function add($scope) {
alert($scope.user.username);
}
});
app.controller('table', function(Service,$scope) {
//get the return data from getData funtion in factory
this.add = Service.add($scope);
});
As you can see I send the scope to factory and I define the user.username as follow:
<button class="btn btn-primary" ng-click="t.add(user.userName)">
But when I run this nothing happens can anyone tell me what is wrong with this code?
<body ng-app="app">
<form>
<div class="row commonRow" ng-controller="table as t">
<div class="col-xs-1 text-right">item:</div>
<div class="col-lg-6 text-right">
<input id="txt" type="text" style="width: 100%;"
ng-model="user.userName">
</div>
<div class="col-xs-2">
<button class="btn btn-primary" ng-click="t.add(user.userName)">
click me</button>
</div>
</div>
</form>
also the plnk link is as follow:
plnkr
The problem is in this line
this.add = Service.add($scope);
Here you are assigning the returned (which is undefined) value of the Service.add($scope) invocation to the this.add.
The right approach will be either
this.add = function(data) { Service.add($scope); }
or
this.add = Service.add;
// in the service factory.
function add(usrNm) {
alert(usrNm);
}
The first thing is you can't use $scope in a service.and in controller your not assaining this(object) to $scope.so $scope doesn't contain any value.
I suppose you to write like this
$scope.user = this;

$dirty not working as expected when the input type is "file"

Am quite new to AngularJS. The issue is i have a form with two fields- name and profile pic as shown in the code below. I am using ng-upload (https://github.com/twilson63/ngUpload). I want the 'Save' button to work only if either field is dirty and the upload isn't happening currently so that multiple post requests are not triggered on the user clicking on the 'Save' button. But looks like, $dirty works fine with the 'name' field but not with the 'profile pic' field. Am i just missing something? How to go about it keeping it as simple as possible for a beginner of AngularJS. Any help would be appreciated.
//Code
<form id='picUpload' name='picUpload' ng-upload-before-submit="validate()" method='post' data-ng-upload-loading="submittingForm()" action={{getUrl()}} data-ng-upload='responseCallback(content)' enctype="multipart/form-data">
<input type="text" name="name" data-ng-model="user.name" maxlength="15" id="user_screen_name" required>
<input type="file" name="profilePic" data-ng-model="user.profilePic" accept="image/*">
<div class="form-actions">
<button type="submit" class="btn primary-btn" id="settings_save" data-ng-disabled="!(picUpload.name.$dirty|| picUpload.profilePic.$dirty) || formUploading">Save changes</button>
</div>
</form>
//In my JS code
$scope.submittingForm = function(){
$scope.formUploading = true;
}
Regards!
I made a directive ng-file-dirty
.directive('ngFileDirty', function(){
return {
require : '^form',
transclude : true,
link : function($scope, elm, attrs, formCtrl){
elm.on('change', function(){
formCtrl.$setDirty();
$scope.$apply();
});
}
}
})
I haven't used ng-upload before, but you can use onchange event of input element. onchange event is fired whenever user selects a file.
<input type="file" onchange="angular.element(this).scope().fileNameChanged(this)" />
Javascript :
var app = angular.module('MainApp', []);
app.controller('MainCtrl', function($scope)
{
$scope.inputContainsFile = false;
$scope.fileNameChanged = function(element)
{
if(element.files.length > 0)
$scope.inputContainsFile = true;
else
$scope.inputContainsFile = false;
}
});
So now you can check if inputContainsFile variable is true along with dirty check of name field

What is the AngularJS way of handling a modal like this

I know you're not supposed to put your display logic inside of a controller and I'm struggling with the proper AngularJS way to approach this.
I'm presenting forms inside modals. I'm using Zurb Foundation's reveal for the modal.
Markup:
<div class="button" ng-click="modalAddWidget">Add Widget</div>
<div id="modalAddWidget" class="reveal-modal">
<h6>New Widget</h6>
<form>
<fieldset>
<legend>Widget Name</legend>
<input type="text" ng-model="ui.add_widget_value" />
</fieldset>
<div class="small button right" ng-click="addWidget()">Add Widget</div>
<div class="small button right secondary" ng-click="addWidgetCancel()">Cancel</div>
</form>
</div>
Controller:
...
$scope.modalAddWidget = function() {
$("#modalAddWidget").reveal();
}
$scope.addWidget = function() {
$scope.myobject.widgets.push({"name": $scope.ui.add_widget_value});
$scope.ui.add_widget_value = '';
$('#modalAddWidget').trigger('reveal:close');
}
$scope.addBudgetCancel = function() {
$scope.ui.add_widget_value = '';
$('#modalAddWidget').trigger('reveal:close');
}
...
Note: $scope.ui is an object I am using to store UI values that shouldn't be bound to my object until the user actually clicks "Add Widget"
$scope.myobj is where my data is stored.
Foundation's $("#modalAddWidget").reveal(); function presents the modal overlay.
Since I shouldn't be putting my display code inside the controller, what is the proper way to approach this?
You don't want to manipulate the DOM (or even reference it) from your controllers.
A directive is best here.
app.directive('revealModal', function (){
return function(scope, elem, attrs) {
scope.$watch(attrs.revealModal, function(val) {
if(val) {
elem.trigger('reveal:open');
} else {
elem.trigger('reveal:close');
}
});
elem.reveal();
}
});
then in your controller:
$scope.modalAddWidget = function (){
$scope.ui = { add_widget_value: '' };
$scope.showModal = true;
};
$scope.addWidget = function (){
$scope.myobject.widgets.push({"name": $scope.ui.add_widget_value});
$scope.ui.add_widget_value = '';
$scope.showModal = true;
};
And in your HTML
<div class="button" ng-click="modalAddWidget()">Add Widget</div>
<div id="modalAddWidget" class="reveal-modal" reveal-modal="showModal">
<h6>New Widget</h6>
<form name="addWidgetForm" ng-submit="addWidget()">
<fieldset>
<legend>Widget Name</legend>
<input type="text" name="widgetValue" ng-model="ui.add_widget_value" required />
<span ng-show="addWidgetForm.widgetValue.$error.required">required</span>
</fieldset>
<button type="submit" class="small button right">Add Widget</button>
<div class="small button right secondary" ng-click="showModal = false;">Cancel</div>
</form>
</div>
Basically you'd set a boolean in your scope to show and hide your modal. (I'm not sure of reveal modal's open/close mechanism, so I'm guessing in my code above).
ALSO: I went through the effort of adding some validation in there.

Dynamic validation and name in a form with AngularJS

I have this form : http://jsfiddle.net/dfJeN/
As you can see the name value for the input is statically set :
name="username"
, the form validation works fine (add something and remove all text from the input, a text must appears).
Then I try to dynamically set the name value : http://jsfiddle.net/jNWB8/
name="{input.name}"
Then I apply this to my validation
login.{{input.name}}.$error.required
(this pattern will be used in an ng-repeat) but my form validation is broken. It is correctly interpreted in my browser (if I inspect the element I saw login.username.$error.required).
Any Idea ?
EDIT: After logging the scope in the console it appears that the
{{input.name}}
expression is not interpolate. My form as an {{input.name}} attribute but no username.
UPDATE: Since 1.3.0-rc.3 name="{{input.name}}" works as expected. Please see #1404
You can't do what you're trying to do that way.
Assuming what you're trying to do is you need to dynamically add elements to a form, with something like an ng-repeat, you need to use nested ng-form to allow validation of those individual items:
<form name="outerForm">
<div ng-repeat="item in items">
<ng-form name="innerForm">
<input type="text" name="foo" ng-model="item.foo" />
<span ng-show="innerForm.foo.$error.required">required</span>
</ng-form>
</div>
<input type="submit" ng-disabled="outerForm.$invalid" />
</form>
Sadly, it's just not a well-documented feature of Angular.
Using nested ngForm allows you to access the specific InputController from within the HTML template. However, if you wish to access it from another controller it does not help.
e.g.
<script>
function OuterController($scope) {
$scope.inputName = 'dynamicName';
$scope.doStuff = function() {
console.log($scope.formName.dynamicName); // undefined
console.log($scope.formName.staticName); // InputController
}
}
</script>
<div controller='OuterController'>
<form name='myForm'>
<input name='{{ inputName }}' />
<input name='staticName' />
</form>
<a ng-click='doStuff()'>Click</a>
</div>
I use this directive to help solve the problem:
angular.module('test').directive('dynamicName', function($compile, $parse) {
return {
restrict: 'A',
terminal: true,
priority: 100000,
link: function(scope, elem) {
var name = $parse(elem.attr('dynamic-name'))(scope);
// $interpolate() will support things like 'skill'+skill.id where parse will not
elem.removeAttr('dynamic-name');
elem.attr('name', name);
$compile(elem)(scope);
}
};
});
Now you use dynamic names wherever is needed just the 'dynamic-name' attribute instead of the 'name' attribute.
e.g.
<script>
function OuterController($scope) {
$scope.inputName = 'dynamicName';
$scope.doStuff = function() {
console.log($scope.formName.dynamicName); // InputController
console.log($scope.formName.staticName); // InputController
}
}
</script>
<div controller='OuterController'>
<form name='myForm'>
<input dynamic-name='inputName' />
<input name='staticName' />
</form>
<a ng-click='doStuff()'>Click</a>
</div>
The problem should be fixed in AngularJS 1.3, according to this discussion on Github.
Meanwhile, here's a temporary solution created by #caitp and #Thinkscape:
// Workaround for bug #1404
// https://github.com/angular/angular.js/issues/1404
// Source: http://plnkr.co/edit/hSMzWC?p=preview
app.config(['$provide', function($provide) {
$provide.decorator('ngModelDirective', function($delegate) {
var ngModel = $delegate[0], controller = ngModel.controller;
ngModel.controller = ['$scope', '$element', '$attrs', '$injector', function(scope, element, attrs, $injector) {
var $interpolate = $injector.get('$interpolate');
attrs.$set('name', $interpolate(attrs.name || '')(scope));
$injector.invoke(controller, this, {
'$scope': scope,
'$element': element,
'$attrs': attrs
});
}];
return $delegate;
});
$provide.decorator('formDirective', function($delegate) {
var form = $delegate[0], controller = form.controller;
form.controller = ['$scope', '$element', '$attrs', '$injector', function(scope, element, attrs, $injector) {
var $interpolate = $injector.get('$interpolate');
attrs.$set('name', $interpolate(attrs.name || attrs.ngForm || '')(scope));
$injector.invoke(controller, this, {
'$scope': scope,
'$element': element,
'$attrs': attrs
});
}];
return $delegate;
});
}]);
Demo on JSFiddle.
Nice one by #EnISeeK.... but i got it to be more elegant and less obtrusive to other directives:
.directive("dynamicName",[function(){
return {
restrict:"A",
require: ['ngModel', '^form'],
link:function(scope,element,attrs,ctrls){
ctrls[0].$name = scope.$eval(attrs.dynamicName) || attrs.dynamicName;
ctrls[1].$addControl(ctrls[0]);
}
};
}])
Just a little improvement over EnlSeek solution
angular.module('test').directive('dynamicName', ["$parse", function($parse) {
return {
restrict: 'A',
priority: 10000,
controller : ["$scope", "$element", "$attrs",
function($scope, $element, $attrs){
var name = $parse($attrs.dynamicName)($scope);
delete($attrs['dynamicName']);
$element.removeAttr('data-dynamic-name');
$element.removeAttr('dynamic-name');
$attrs.$set("name", name);
}]
};
}]);
Here is a plunker trial. Here is detailed explantion
I expand the #caitp and #Thinkscape solution a bit, to allow dynamically created nested ng-forms, like this:
<div ng-controller="ctrl">
<ng-form name="form">
<input type="text" ng-model="static" name="static"/>
<div ng-repeat="df in dynamicForms">
<ng-form name="form{{df.id}}">
<input type="text" ng-model="df.sub" name="sub"/>
<div>Dirty: <span ng-bind="form{{df.id}}.$dirty"></span></div>
</ng-form>
</div>
<div><button ng-click="consoleLog()">Console Log</button></div>
<div>Dirty: <span ng-bind="form.$dirty"></span></div>
</ng-form>
</div>
Here is my demo on JSFiddle.
I used Ben Lesh's solution and it works well for me. But one problem I faced was that when I added an inner form using ng-form, all of the form states e.g. form.$valid, form.$error etc became undefined if I was using the ng-submit directive.
So if I had this for example:
<form novalidate ng-submit="saveRecord()" name="outerForm">
<!--parts of the outer form-->
<ng-form name="inner-form">
<input name="someInput">
</ng-form>
<button type="submit">Submit</button>
</form>
And in the my controller:
$scope.saveRecord = function() {
outerForm.$valid // this is undefined
}
So I had to go back to using a regular click event for submitting the form in which case it's necessary to pass the form object:
<form novalidate name="outerForm"> <!--remove the ng-submit directive-->
<!--parts of the outer form-->
<ng-form name="inner-form">
<input name="someInput">
</ng-form>
<button type="submit" ng-click="saveRecord(outerForm)">Submit</button>
</form>
And the revised controller method:
$scope.saveRecord = function(outerForm) {
outerForm.$valid // this works
}
I'm not quite sure why this is but hopefully it helps someone.
This issue has been fixed in Angular 1.3+
This is the correct syntax for what you are trying to do:
login[input.name].$invalid
if we set dynamic name for a input like the below
<input name="{{dynamicInputName}}" />
then we have use set validation for dynamic name like the below code.
<div ng-messages="login.dynamicInputName.$error">
<div ng-message="required">
</div>
</div>

Resources