ng-model in input based on another variable - javascript

I han an input filed in my angular app <input type="text" ng-model="variableA">. I want to use variableA or variableB basing on some condition. I've tried something like this ng-model="condition ? variableA : variableB" but it throws Error: [ngModel:nonassign]. Any ideas how to make it work?

You could make use of ngModelOptions:
<input type="text" ng-model="setModel" ng-model-options="{getterSetter: true}">
In your controller:
$scope.setModel = function(value) {
var model = '';
if (condition) {
model = "variableA";
} else {
model = "variableB";
}
if (angular.isDefined(value)) {
return ($scope[model] = value);
} else {
return $scope[model];
}
};

ngModel has to be a property expression (following the fules of $parse).
Try using a proxy then watch that variable to then assign to A or B:
<input type="text" ng-model="variableC">
In your controller:
$scope.$watch('variableC', function(value) {
if(someCondition) {
$scope.variableA = value;
} else {
$scope.variableB = value;
}
});

How about
<input type="text" ng-model="variableC">
and in controller
$scope.variableC = (condition) ? variableA : variableB

Related

How to bind a value from one ng-model to an other by matching a specific string

I got a requirement to bind a value to a particular model when the value in the other model contains a string starting with "https".
For example, I have two text fields both fields having different model
<input type="text" ng-model="modelText1">
<input type="text" ng-model="modelText2">
Suppose I type a value on the first text field "https", the first input model modelText1 have to bind to the second input model modelText2 and later on i have to maintain it as like two-way binding. i.e. the second field will automatically get the value dynamically when it contains "https" at starting of a string.
Try it like in this Demo fiddle.
View
<div ng-controller="MyCtrl">
<input type="text" ng-model="modelText1">
<input type="text" ng-model="modelText2">
</div>
AngularJS Application
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope) {
$scope.modelText1 = '';
$scope.modelText2 = '';
var regEx = new RegExp(/^https/);
$scope.$watch('modelText1', function (newValue) {
if (newValue.toLowerCase().match(regEx)) {
$scope.modelText2 = newValue;
} else {
$scope.modelText2 = '';
}
});
});
An other approach is (that avoid using of $watch) is to use AngularJS ng-change like in this
example fiddle.
View
<div ng-controller="MyCtrl">
<input type="text" ng-model="modelText1" ng-change="change()">
<input type="text" ng-model="modelText2">
</div>
AngularJS Application
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope) {
$scope.modelText1 = '';
$scope.modelText2 = '';
var regEx = new RegExp(/^https/);
$scope.change = function () {
if ($scope.modelText1.toLowerCase().match(regEx)) {
$scope.modelText2 = $scope.modelText1;
} else {
$scope.modelText2 = '';
}
};
});
You can use the ng-change directive like this:
<input type="text" ng-model="modelText1" ng-change="onChange()">
<input type="text" ng-model="modelText2">
and your controller:
$scope.onChange = function() {
if ($scope.modelText1 === 'https') {
$scope.modelText2 = $scope.modelText1;
else
$scope.modelText2 = '';
};
use ng-change to check the text is equal to 'https'
angular.module('app',[])
.controller('ctrl',function($scope){
$scope.changeItem = function(item){
$scope.modelText2 = "";
if(item.toLowerCase() === "https"){
$scope.modelText2 = item
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<input type="text" ng-model="modelText1" ng-change="changeItem(modelText1)">
<input type="text" ng-model="modelText2">
</div>
EDiTED
to make sure it does't fail under 'HTTPS' use toLoweCase function to make all lower case
HTML :
<input type="text" ng-model="modelText1" ng-change="updateModal(modelText1)">
JS :
var modelText1 = $scope.modelText1.toLowerCase();
$scope.updateModal = function(){
$scope.modelText2 = '';
if(modelText1.indexOf('https')!=-1){
$scope.modelText2 = modelText1;
}
}
you could also possibly do this as a directive if you want to have a more reusable solution over multiple views http://jsfiddle.net/j5ga8vhk/7/
It also keeps the controller more clean, i always try to use the controller only for controlling complex business logic and business data
View
<div ng-controller="MyCtrl">
<input type="text" ng-model="modelText1" >
<input type="text" ng-model="modelText2" model-listener="modelText1" model-listener-value="https" >
</div>
Angular JS
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope) {
$scope.modelText1 = '';
$scope.modelText2 = '';
});
myApp.directive('modelListener', [function() {
return {
restrict: 'A',
controller: ['$scope', function($scope) {
}],
link: function($scope, iElement, iAttrs, ctrl) {
$scope.$watch(iAttrs.modelListener, function() {
if($scope[iAttrs.modelListener] === iAttrs.modelListenerValue ) {
$scope[iAttrs.ngModel] = $scope[iAttrs.modelListener];
} else {
$scope[iAttrs.ngModel] = "";
}
}, true);
}
};
}]);

AngularJs - facing an issue when using ng-init

I am facing an issue with using ng-init and assign it model inside my html.
The following code works fine. The following code is for Add/Edit functionality. For example, when row is is opened in Edit mode than it persist existing value and shows it in textbox.
<div>
<div ng-if="title == 'Add Student'">
<input type="text" name="name"placeholder="Student Name" data-ng-model="registration.Student.FirstName" maxlength="50">
</div>
<div ng-if="title == 'Edit Student'">
<input type="text" name="name"placeholder="Student Name" data-ng-model="student.Student.FirstName" maxlength="50">
</div>
</div>
However, the following code which is short version of above code does not work. I mean when the row is opened in edit mode it shows text field but does not show existing value (first name) in it. Why?
<div ng-init="model = (title == 'Add Student' ? registration.Student : student.Student)">
<input type="text" name="name" placeholder="Student Name" data-ng-model="model.FirstName" maxlength="50">
</div>
Please suggest whether ng-init can't be used in this way or some issue in my code?
thanks
Controller
var currentState = $state.current.name;
if if (currentState == "Add")
{
$scope.registration = {
Student: {
FirstName: '',
}
var _init = function () {
}
$scope.title = " Add Student";
}
else
{
$scope.student= {};
$scope.student= response[0];
var _init = function () {
$scope.title = " Edit Student";
}
}
You are ng-init block is wrong currently it is returning true or false, you are messing with brackets.
Markup
<div ng-init="model = (title == 'Add Student') ? registration.Student : student.Student">
<input type="text" name="name" placeholder="Student Name" data-ng-model="model.FirstName" maxlength="50">
</div>
Update
In your current case you ng-init is getting executed while element rendered on the DOM, at that instance on time registration.Student & student.Student doesn't have any value. Evaluation of ng-init setting null object to the model student. I'd suggest you do set model value from the controller logic that would be more safer.
Code
var currentState = $state.current.name;
if (currentState == "Add")
{
$scope.registration = {
Student: {
FirstName: '',
}
var _init = function () {
}
$scope.title = " Add Student";
}
else
{
$scope.student= {};
$scope.student= response[0];
var _init = function () {
$scope.title = " Edit Student";
}
//shifted logic in controller
$scope.model = (title == 'Add Student' ? registration.Student : student.Student);
}
Markup
<div>
<input type="text" name="name" placeholder="Student Name"
data-ng-model="model.FirstName" maxlength="50"/>
</div>
Other way you could add one more flag like loadedData which will says that ajax response has been fetched & registration.Student & student.Student values are available in the scope.
Markup
<div ng-if="loadedData">
<input type="text" name="name" placeholder="Student Name" data-ng-model="model.FirstName" maxlength="50">
</div>
Code
var currentState = $state.current.name;
if (currentState == "Add")
{
$scope.registration = {
Student: {
FirstName: '',
}
var _init = function () {
}
$scope.title = " Add Student";
}
else
{
$scope.student= {};
$scope.student= response[0];
var _init = function () {
$scope.title = " Edit Student";
}
//set flag
$scope.loadedData = true;
}

how to pass values from localStorage to input field

I'm trying to pass localStorage to input field, but i'm not able to pass the values, i not getting where i'm going wrong, please help me with this, 1 thing more how can i call the angularjs function outside the controller. thanx for any help guys.
html
<div class="modal__content" ng-controller="joinctrl">
<form novalidate>
<input type="email" placeholder="Email" ng-model="email"><br />
<input type="password" placeholder="Password" ng-model="password"><br />
<input type="password" placeholder="Confirm Password" ng-model="cpassword"><br />
<input type="submit" value="Create" class="creat" ng-click="create()">
</form>
</div>
js
preauth();
function preauth() {
var user_login = window.localStorage.getItem('email');
var pass_login = window.localStorage.getItem('password');
if(user_login != undefined && pass_login != undefined) {
alert(user_login);
document.getElementById("email").value=user_login;
document.getElementById("password").value=pass_login;
angular.element(document.getElementById('loginctrl')).scope().Login();
}
}
var app = angular.module('contol', ['onsen']);
app.controller('loginctrl', function($scope, $http){
$scope.login=function(){
if (!$scope.email || !$scope.password){
alert("Please Fill Email & Password");
}
else{
var request=$http({
method:"post",
url:"http://www.example.com/login.php",
dataType: "json",
data:{
email:$scope.email,
password:$scope.password
},
headers:{'Content-Type':'application/x-www-form-urlencoded'}
});
request.success(function(retmsg){
if(parseInt(retmsg.status)==0)
{
alert(retmsg.txt);
}
else if (parseInt(retmsg.status)==1)
{
window.localStorage.setItem('email', $scope.email);
window.localStorage.setItem('password', $scope.password);
myNavigator.pushPage('home.html');
}
});
}
};
});
This may be useful,store it in variable and use it and only id name not #password
var x = document.getElementById("password").value = "Password";
alert ("The value was changed to: " + x);
In Angular applications, you should write ALL code inside modules. Otherwise, you don't use one of the useful feature of Angular: modularity.
For example:
app.factory("LocalStorage", function() {
var LS = {};
LS.getItem = function(key) {
return localStorage[key];
};
LS.setItem = function(key, value) {
localStorage[key] = value;
return value;
};
return LS;
});
app.controller('loginctrl', function($scope, $http, LocalStorage) {
$scope.email = LocalStorage.getItem('email');
$scope.password = LocalStorage.getItem('password');
$scope.login = function() {
// code...
// I'd rather to create another service "Api" or "Request", like this:
return Api.doAuth($scope.login, $scope.password).then(function(res) {
// For example, service `Request` write to `LocalStorage` status of current authentication.
if(res) {
myNavigator.pushPage('home.html');
}
});
};
});
You should not to call function in outside application (it's incorrect from the point of view Angular's philosophy). However, it's possible, you wrote right:
// get our scope:
var scope = angular.element(document.getElementById('loginctrl')).scope();
// and call our function in the scope:
scope.login();
But it's code you need to execute after Angular's bootstrap.
Also, you may to execute any function with Angular's services.
//find the `ng:app` element and get injector.
var injector = angular.element('body').injector();
//execute our own function with any services
injector.invoke(function($rootScope, $http, LocalStorage) {
$http.get('/foo.php').then(function(res) {
LocalStorage.setItem('answer', res);
});
$rootScope.bar = 1;
});

Angular JS Dynamic Model

What I'm trying to do here is when I type in a text in the MainField, I want DateField and NumberField to be enabled. I want the $scope.enableSubFields to be generic so it can be used as a utility. ( The controller does not work, Im only trying to show what I kind of like want :) )
Here's my HTML :
<div>
<label>IF THIS HAS TEXT THEN ENABLE DATE AND NUMBER FIELD</label>
<input type="text" ng-model="MainField" ng-change="enableSubFields('MainField','Subfield')"/>
</div>
<div>
<label>DATE FIELD</label>
<input type="text" ng-model="DateField" ng-disabled="Subfield"/>
</div>
<div>
<label>NUMBER FIELD:</label>
<input type="text" ng-model="NumberField" ng-disabled="Subfield"/>
</div>
Heres my Controller
$scope.Subfield= true;
$scope.enableSubFields = function (mainField, subfield) {
if ($scope + '.' + mainField != "") {
$scope + '.' + subfield = false;
} else {
$scope + '.' + subfield = true;
}
};
You need to use a bracket notation to access dynamic properties of an object. So your code should be:
$scope.enableSubFields = function(mainField, subfield) {
if ($scope[mainField] !== "") {
$scope[subfield] = false;
} else {
$scope[subfield] = true;
}
};
or shorter:
$scope.enableSubFields = function(mainField, subfield) {
$scope[subfield] = $scope[mainField] == "";
};
Demo: http://plnkr.co/edit/IbVzrPFEf624JiG6hIrC?p=preview

Knockout.js conditional binding

How do you have conditional binding based on other properties?
Example..
var ViewModel = {
IsAdded = ko.observable(),
AddedBy = ko.observable()
}
When I display it.. I don't want to show AddedBy if IsAddedBy is null or false
Something like this..
&ltinput type="text" data-bind="value: if (IsAdded != null && IsAdded) { AddedBy }"/>
I know that isn't right, but something like that...
What I would do is this;
var ViewModel = function() {
this.IsAdded = ko.observable('True');
this.AddedBy = ko.observable('Test');
this.AddedByText = ko.computed(function(){
if ( this.AddedBy() != null && this.IsAdded() ) return this.AddedBy()
return "";
}, this);
}
Then your input would be
<input type="text" data-bind="value: AddedByText" />
This way you are keeping the logic contained within your ViewModel and separate from the HTML.
This question is old but it might help someone else looking
<input type="text" data-bind="value: IsAdded ? AddedBy : "" "/>
Basically if IsAdded is not null then set the value to AddedBy, else do nothing

Categories

Resources