Can't access form variable from my controller, when i try to access it by $scope.locationForm i've got 'undefined', but when i call console.log($scope) i can see in console there have loactionForm.
My HTML code
<div ng-controller="LocationsController as ctrl">
<form class="form-inline" name="locationForm">
<div class="form-group">
<!-- <div class="input-group"> -->
<label for="location-name">Название населенного пункта</label>
<input required
name="name"
ng-model="ctrl.location.name" type="text" class="form-control" id="location-name" placeholder="Название населенного пункта">
<label for="location-name">Район</label>
<select required
name="region_id"
ng-model="ctrl.location.region_id"
ng-options="region.id as region.name for region in ctrl.regions" class="form-control" placeholder="Название района"></select>
<input ng-click="ctrl.save()"
ng-disabled="locationForm.$invalid" type="submit" class="btn btn-default" value="Cохранить">
<a class="btn btn-default" ng-click="ctrl.reset()" ng-show="locationForm.$dirty">Сброс</a>
<!-- </div> -->
</div>
</form>
My Controller code:
function LocationsController($scope, Location, Region, $q) {
var lc = this,
l_index;
lc.form ={};
lc.regions = lc.locations = [];
lc.regions = Region.query();
lc.regions.$promise.then(function(data) {
lc.locations = Location.query();
});
lc.getRegion = function (id) {
return lc.regions.filter(function(obj) {
return obj.id == id;
})[0].name;
};
console.log($scope);
// console.log($scope.locationForm);
lc.reset = function () {
lc.location = new Location;
}
lc.reset();
};
The problem is when the LocationsController is initialized the form element is not yet compiled. So one possible hack is to use a timeout like
function LocationsController($scope, Location, Region, $q, $timeout) {
//then later
$timeout(function(){lc.reset();})
}
Related
ng-app is added in the html tag. I have added just a portion of html code.
I am trying to use the CreatePortfolioController but it seems to be undefined. I checked for typo errors too, but there seems to be none. I have no idea why it is not working. Can you please help me debug?
App.js
var app = angular.module("UiApp", ["ServiceApp"]);
app.service('sharedProperties', function () {
var idValue = 'test string value';
return {
getId: function () {
return idValue;
},
setId: function (value) {
idValue = value;
}
}
});
app.controller("PortFolioController", function ($scope, GetPortfolios, sharedProperties) {
$scope.Portfolios = GetPortfolios.query({ pmid: 2 });
console.log($scope.Portfolios);
$scope.addOrder = function (id) {
sharedProperties.setId(id)
};
});
app.controller("CreatePortfolioController", function ($scope, CreatePortfolio) {
$scope.create = function (data) {
CreatePortfolio.save(data);
};
});
app.controller("OrderController", function ($scope, GetOrders, sharedProperties) {
$scope.$watch(function () {
return sharedProperties.getId()
}, function (newValue, oldValue) {
if (newValue != oldValue) {
$scope.item = newValue;
$scope.Orders = GetOrders.query({ id: item });
}
});
});
Service.js
var app = angular.module("ServiceApp", ["ngResource"]);
app.factory('GetPortfolios', function ($resource) {
return $resource("http://localhost:61347/api/PortfolioManager/GetPortfolios/");
});
app.factory('GetOrders', function ($resource) {
return $resource("http://localhost:61347/api/PortfolioManager/GetPortfolioOrders/");
});
app.factory('CreatePortfolio', function ($resource) {
return $resource("http://localhost:61347/api/PortfolioManager/CreatePortfolio");
});
Html
<div class="panel-body">
<div class="form" ng-controller="CreatePortfolioController">
<form class="cmxform form-horizontal " id="signupForm" method="get" ng-submit="create(data)" action="">
<div class="form-group ">
<label for="portfolioname" class="control-label col-lg-3">Portfolio Name</label>
<div class="col-lg-6">
<input class= "form-control" ng-model="data.portfolioName" name="portfolioname" type="text" required />
</div>
</div>
<div class="form-group ">
<label for="portfoliotype" class="control-label col-lg-3">Portfolio Type</label>
<div class="col-lg-6">
<input class= "form-control" ng-model="data.type" name="portfoliotype" type="text" required />
</div>
</div>
<div class="form-group ">
<label for="portfoliodesc" class= "control-label col-lg-3">Portfolio Description</label>
<div class="col-lg-6">
<textarea class="form-control " ng-model="data.description" name="portfoliodesc" rows="3"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-3 col-lg-6">
<button class="btn btn-primary" type="submit">Save <i class="fa fa-check"></i></button><!--Write Save code-->
<button class="btn btn-primary" type="reset">Cancel <i class="fa fa-times"></i></button><!--Write clear text box code-->
</div>
</div>
</form>
</div>
</div>
Sequence of imported files
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/angular-resource.js"></script>
<script src="~/AngularScripts/PM/App.js"></script>
<script src="~/AngularScripts/PM/Service.js"></script>
Please check all these conditions:
Your ng-app is included before the ng-controller in HTML page or
together in the same tag.
Check the name of controller as it is case sensitive.
Make sure you have loaded the JS files properly inside the HTML page. The JS file for AngularJS library, then your app files that
contains, sequentially- JS file with ng-app set, js files that
define services (if any), js files that define factories (if any) ,
js files that define your controllers. Be sure you don't miss to
include any js files and are in proper sequence.
As i do not see controller file included in the <script>, in the snippet you have added.
I seem to be overlooking something simple here but it has me stumped.
Why does nothing happen when i hit the submit button?
<section ng-controller="SavingsController as savingsCTRL">
<form name="createSavingForm" class="form-horizontal" novalidate>
<fieldset>
<!-- Title Box Start-->
<div class="form-group new-deal-form" show-errors>
<label for="title">Title</label>
<input name="title" type="text" ng-model="savingsCTRL.title" id="title" class="form-control" placeholder="Title" required>
<div class="sub-label">Enter the Title of the Deal.</div>
<div ng-messages="savingForm.savingsCTRL.title.$error" role="alert">
<p class="help-block error-text" ng-message="required">Saving title is required.</p>
</div>
</div>
<!-- Title Box End-->
<!--Submit Button Start-->
<div class="form-group buttons-cancel-submit">
<button class="btn btn-default " ng-click="savingsCTRL.cancel()">Cancel</button>
<input type="submit" class="btn btn-success " ng-click="savingsCTRL.create(); submitForm(createSavingForm.$valid)" >
</div>
</fieldset>
</form>
</div>
</div>
</section>
for simplicity i took most of the forms out but what else is wrong?
Savings Controller Function
// Create new Saving
$scope.create = function () {
$scope.error = null;
alert("create");
// Create new Saving object
var saving = new Savings({
title: this.title,
details: this.details,
retailer: this.retailer,
price: this.price,
link: this.link,
image: $scope.user.imageURL,
urlimage: this.urlimage,
tags: this.tags
//startdate: this.startdate,
//enddate: this.enddate
});
// Redirect after save
saving.$save(function (response) {
$location.path('savings/' + response._id);
// Clear form fields
$scope.title = '';
$scope.details = '';
$scope.retailer = '';
$scope.price = '';
$scope.link = '';
$scope.image = '';
$scope.urlimage = '';
$scope.tags = '';
}, function (errorResponse) {
$scope.error = errorResponse.data.message;
});
};
Main issue is, you are mixing controller as syntax with $scope.
According to documentation, we should use this instead of $scope.
... binds methods and properties directly onto the controller using this: ng-controller = "SettingsController1 as settings"
Than, submitForm is not a predefined method, it should be defined in controller first
this.submitForm = function(isValid){
console.log('Submitting form: ' + isValid)
}
In addition to that, bind that to form with ng-submit= "savingsCTRL.submitForm(createSavingForm.$valid)"
See Plunker, with working code. (I took ng-click="savingsCTRL.create()", since we don't have all parts of your application)
Bind the form submit event to ng-submit.
Example: ng-submit="submitForm(createSavingForm.$valid)"
I use the angularjs framework, I created an form.html and a controller.js with a variable that retrieves the SSID of a box.
How to automatically assign the value of the variable in the form.
This is an input field.
When launching the application, the form should display the SSID automatically without the user needing to do so.
Thank you kindly help me.
'use strict';
angular.module('djoro.controllers')
.controller('WifiSmartConfigCtrl', function ($scope, $window, $ionicPlatform) {
$scope.getSSID = function () {
var onSuccess = function (SSID) {
document.write(SSID);
};
var onFail = function () {
};
$ionicPlatform.ready(function () {
$window.cordova.plugins.Smartconfig.getSSID(onSuccess, onFail);
});
};
});
<ion-pane>
<ion-content ng-controller="WifiSmartConfigCtrl">
<form novalidate class="simple-form">
<fieldset>
<legend>WI-FI</legend>
<div class="list input-fields">
<label class="item item-input">
<span class="input-label">SSID :</span>
<input type="text" name="test" value="getSSID()" required show-hide-input>
</label>
<label class="item item-input" show-hide-container>
<span class="input-label">Password :</span>
<input type="text" name="password" required show-hide-input>
</label>
</div>
</fieldset>
</form>
</ion-content>
</ion-pane>
use the ng-model directive, it's exactly it's purpose :
'use strict';
angular.module('djoro.controllers')
.controller('WifiSmartConfigCtrl', function($scope, $window, $ionicPlatform) {
$scope.SSID = {};
$scope.getSSID = function() {
var onSuccess = function(SSID) {
$scope.SSID = SSID;
};
var onFail = function() {};
$ionicPlatform.ready(function() {
$window.cordova.plugins.Smartconfig.getSSID(onSuccess, onFail);
});
};
});
and in your view :
<input type="text" name="test" ng-model="SSID" required show-hide-input>
You need to add an ng-model to the input field like so:
<label class="item item-input">
<span class="input-label">SSID :</span>
<input type="text" name="test" ng-model="SSID" required show-hide-input>
</label>
then in your controller assign the value of SSID on the $scope:
$scope.SSID = [some_value]
see this plnkr
As you can see I have assigned the value of SSID manually, you can add it dynamically by assigning it in the callback of your function like so:
$scope.SSID = {}
var onSuccess = function (SSID) {
document.write(SSID);
$scope.SSID = SSID
};
I'm trying to code a controller so some inputs get disabled after changes in another one.
This is the controllre:
app.controller('SignUpController',function ($scope, $http) {
this.unavaliable = true
this.userUnavaliable = function() {
console.log(this.unavaliable)
return this.unavaliable
}
this.userExists = function(mail) {
if (mail) {
var who = $http.get("/existingUsers/"+mail)
who.success(function(data,status, headers, config) {
if (data.mail) {
this.unavaliable = true
console.log(data.mail + " ya existe en la DB")
}
else{
this.unavaliable = false
}
});
who.error(function(data, status, headers, config) {
alert("AJAX failed!");
})
}
}
})
As my markup below shows, one input should obtain a certain class, and another one should get disabled when unavaliable is set to true. But even I can get to the console.log(), the variable seems to never get true.
This is my markup:
<form class="form-inline" role="form">
<div class="form-group">
<input type="email" class="form-control input-lg" ng-model="signup.mail" placeholder="e-mail" ng-change="signup.userExists(signup.mail)" ng-class="{'has-error':signup.userUnavaliable()}">
</div>
<div class="form-group">
<input type="password" class="form-control input-lg" placeholder="Contraseña" ng-nodel="signup.password">
</div>
<div class="checkbox">
<label>
<input type="checkbox" ng-model="signup.role" value="admin"> Administrador
</label>
</div>
<button type="submit" class="btn btn-primary" ng-disabled="signup.unavaliable" >Registrar</button>
</form>
I tried with $scope instead of this but never got it to work that way
Try this:
app.controller('SignUpController',function ($scope, $http) {
var that = this;
that.unavaliable = true;
that.userUnavaliable = function() {
console.log(that.unavaliable)
return that.unavaliable
}
that.userExists = function(mail) {...
Your issue seems to be related to JS Context; in the example above it is preserved in that variable. That is how it is done in JOhn's Papa approach
I have this form below. When I change the text fields, it shows the changes here
<div>
{{authform.email}}{{authform.password}}
</div>
but when I try to submit the form by ng-click="signup()" on a button, it doesn't send me the value of text fields.
below is my code
<div class="col-md-12" ng-controller="authCtrl">
<div class="row">
<div class="col-md-14">
<div class="jumbotron">
<form>
<div class="createUserDiv"><input type="text" name="email" placeholder="enter your email address" ng-model="authform.email"/></div>
<div class="createUserDiv"><input type="text" name="password" placeholder="enter your password" ng-model="authform.password"/></div>
<div class="createUserDiv"><input type="text" name="confirmpassword" placeholder="confirm your password" ng-model="authform.confirmpassword"/></div>
<p><a class="btn btn-lg btn-success" ng-click="signup()">Splendid!<span
class="glyphicon glyphicon-ok"></span></a></p>
</form>
<div>
{{authform.email}} {{authform.password}}
</div>
</div>
</div>
</div>
</div>
here is my js
angular.module('myAPP')
.controller('authCtrl', function ($scope, $http, $location) {
$scope.signup = function() {
$scope.authform = {};
$scope.authform.email = "";
$scope.authform.password = "";
$scope.authform.confirmpassword = "";
var data = {
"dataBlob": {
"email": $scope.authform.email,
"password": $scope.authform.confirmpassword
}
};
console.log($scope.authform.email);
});
my console.log is coming up empty ...null....I am not sure why is it not binding the fields to data. I am pretty new to angular so I am still trying to figure out these things.
Stat your controller like this:
angular.module('myAPP')
.controller('authCtrl', function ($scope, $http, $location) {
$scope.authForm = {};
Then change your signup method to do this:
$scope.signup = function() {
console.log($scope.authForm);
}
Your values are already bound, but when you called $scope.authForm = {}; inside of signup, you are overwriting all of your values.
Also instead of ng-click="signup()" on your button, do this:
<form ng-submit="signup()">
Which will allow you to implement validations and submit on [enter] keypress when the user in an input field
For an example, see this fiddle