Pass Model to Controller to Change in Controller - javascript

Here is my situation, I have this HTML:
<input type="text" ng-model="inputModel" />
<div class="button-container">
<button type="button" ng-click="setValue(inputModel)"></button>
</div>
<input type="text" ng-model="inputModelTwo" />
<div class="button-container">
<button type="button" ng-click="setValue(inputModelTwo)"></button>
</div>
And my view controller:
$scope.setValue = function (valueToSet) {
valueToSet = "Some value.";
};
I need to be able to "connect" the input fields and their buttons and I'm doing this by having the respective button pass the respective input field's model to the controller to be modified. The problem is that when I click the button the function fires off and valueToSet is changed but the change isn't reflected back in the view! What am I missing?

If you are trying to dynamically pass in your models as a function parameter, you'll need to access a PROPERTY on the models by using dot notation.
Try defining the models in the controller like so:
$scope.inputModel = {};
$scope.inputModelTwo = {};
$scope.inputModel.text = 'hey';
$scope.inputModelTwo.text = 'ho';
Then pass in the entire model to the function as you were already doing.
Inside the function, alter the property that you desire (in this case 'text'), like so:
$scope.setValue = function (valueToSet) {
console.log(valueToSet);
valueToSet.text = "Some value.";
};
JSFiddle

Related

How to reset all Models on click event?

My requirement: Have to reset my select boxes on button click
Example :-
I have 3 select boxes. When I click on the select box some different data will come and after that the result will get published. I added a Remove button which resets only its parent select box. Now, what I want to know is,how to reset all the three select box on clicking the remove button.
sample code is as under :-
<button ng-click="removeObj(key,model1,0)">Remove</span></button>
controller code is as under :-
scope.removeObj = function(modelID, subModelID, selectBoxPos) {
modelID = 0;
subModelID = 0;
})
I want on click of removeObj function all modelID data get reset to zero.
Please help.
As I understand you do not need any parameters.. only create a meaningful name resetModels:
AngularJS Controller:
$scope.resetModels = function() {
// Set default value to your models...
$scope.modelID = 0;
$scope.subModelID = 0;
});
Html:
<button ng-click="resetScpeModels()">Remove</span></button>
If you want to reset all the values. You should use it like this
$scope.model = {};
$scope.model.modelID = 0;
$scope.model.subModelID = 0;
<input ng-model="model.modelID"/>
If you want to reset it. Call again
$scope.model = {};
Inside ng-click function.
When you give a name to your form it automatically gets added to the $scope.
In angular we are having a $setPristine() method on the $scope.formName. which should recursively take care of resetting your form.
You can reset a form by, $scope.formName.$setPristine(); but if you're binding a model object to your inputs, you need to take care of clearing those too, ie:
$scope.formModel={}; or angular.copy({}, formModel);
Working demo :
var app = angular.module('myApp', []);
app.controller('myController', function($scope) {
$scope.Reset = function(formModel) {
angular.copy({}, formModel);
$scope.formModel = {};
$scope.submitForm.$setPristine();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<form name="submitForm" ng-controller="myController">
<label for="first_field">First Model</label>
<input ng-model="formModel.firstModel" />
<br />
<label for="second_field">Second Model</label>
<input ng-model="formModel.secondModel" />
<br />
<button type="button" ng-click="Reset(formModel)">Reset</button>
</form>
</div>

How to bind current object to text input?

MessageModel
function MessageModel(content) {
var self = this;
self.content = content;
}
RoomViewModel
self.currentMessage = ko.observable(new MessageModel(""));
self.addMessage = function () {
self.messages.push(self.currentMessage());
self.currentMessage(new MessageModel(""));
};
View
<form data-bind="submit: addMessage">
<input data-bind='value: currentMessage.content, valueUpdate: "afterkeydown"' />
<button id="ButtonSendMessage" type="submit">Send</button>
</form>
When user types in input box want the current message content property to update and when I click add I want the currentMessage to be added with content. But the content is always blank.
Maybe because the content isn't an observable and the value bind is wrong beacuse currentMessage is an observable so to bind any property of you must to do like currentMessage().prop or use the with: currentMessage binding in an element context, try something like this:
function MessageModel(content) {
var self = this;
self.content = ko.observable(content);
}
And also i suggest you to use the textInput bind:
<form data-bind="submit: addMessage">
<input type="text" data-bind='textInput: currentMessage().content' />
<button id="ButtonSendMessage" type="submit">Send</button>
</form>
textInput Binding:
The textInput binding links a text box () or text area () with a viewmodel property, providing two-way updates between the viewmodel property and the element’s value. Unlike the value binding, textInput provides instant updates from the DOM for all types of user input, including autocomplete, drag-and-drop, and clipboard events.
Ref:TextInput Bind

Get value input form

I would like to retrieve the password value type for the display in the console.log .
I use a html form with ng-model="passwd" to retrieve the value.
And I then uses a controller with $scope.passwd=null; to retrieve the input field.
For now, $scope.passwd remains null in google chrome => Console
'use strict';
angular.module('djoro.controllers')
.controller('WifiSmartConfigCtrl', function($scope, $window, $ionicPlatform){
$scope.passwd = null;
$scope.startSmartconfig = function(passwd){
var onSuccess = function(success){
$scope.passwd = passwd;
};
var onFail = function(){};
$ionicPlatform.ready(function(){
$window.cordova.plugins.Smartconfig.startSmartconfig(onSuccess, onFail, $scope.passwd);
console.log('Password = ' + $scope.passwd);
});
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form name="wifi_form" class="simple-form">
<div class="list input-fields">
<label class="item item-input" show-hide-container>
<span class="input-label">Password : </span>
<input type="password" name="password" ng-model="passwd" id="passwd" show-hide-input>
</label>
</div>
</form>
<div class="startWifi">
<button class="button button-full button-balanced" ng-click="startSmartconfig()">Start</button>
</div>
Someone an idea to edit the entered value ?
Thank you
Replace $scope.passwd = null; to $scope.passwd = '';
You are using ng-click="startSmartconfig()" and passing nothing but in controller, you have used $scope.startSmartconfig = function(passwd){ so this code will not work.
Set controller function to $scope.startSmartconfig = function(){ and another thing is angularjs is two way binding means when you add value in input text with ng-model="passwd", it also bind the textbox value to $scope.passwd.
I am not aware of $window.cordova thing but what I observed is you didn't pass passwd in ng-click="startSmartconfig()" in html and you are assigning the passwd to $scope.passwd which will be undefined.
And no need to pass passwd in function. You can directly get updated value in $scope.passwd

AngularJS - Find all ngModel in the current scope

I have a HTML template like this:
<div ng-controller="MyCtrl">
<input ng-model="model.name" /> {{model.addr}}
<button ng-click="detect()">detect</button>
</div>
And this is the controller:
function MyCtrl($scope) {
$scope.detect = function() {
var fields = []; //['model.name', 'model.addr']
//call server with selected fields
}
}
The template can be customized by user and generated dynamically, not static template. I want to optimize the data model returned from server, only return values for needed fields in the template. The idea is I want to get all the ng-model fields from template and pass them to the server. The returned data will contain only values for these fields, instead of whole data model, for example:
{
name: 'Superhero',
addr: 'Mars'
}
If I change the template like this (remove model.addr):
<div ng-controller="MyCtrl">
<input ng-model="model.name" />
<button ng-click="detect()">detect</button>
</div>
The fields array should be ['model.name'] and the returned data from the server should be:
{
name: 'Superhero'
}
There are any ways to get all ng-model fields in the scope?
Thanks!
You can do 1 thing, wherever you are using ng-modal, take an object modal and assign values by using dot(.).
Suppose
<div ng-controller="MyCtrl">
<input ng-model="model.name1" />
<input ng-model="model.name2" />
<input ng-model="model.name3" />
<button ng-click="detect()">detect</button>
So you can get model in scope hence all the attributes of scope.

Angularjs ng-required call function

It is possible make the required value dependet of some funcion?
Something like this? I want to do this because I want to change the required attribute to some form inputs...
HTML:
Name: <input type="text" ng-model="user.name" ng-required="isRequired('name')" />
Age: <input type="text" ng-model="user.age" ng-required="isRequired('age')" />
JS:
$scope.isRequired(fieldName){
$scope.requiredFields = [];
//$scope.requiredFields = STUFF FROM SOME REST SERVICE
for (i in requiredFields) {
if (requiredFields[i] == fieldName){
return true;
}
}
return false;
}
Updated Answer:
So based on your updated OP, what you want is certainly doable. The problem with what you were trying to do is that ng-required has no ability to execute a function, it only reads a boolean. But we can dynamically create variables based on data from the server to automatically set fields to required:
Updated Plunker
<form>
Name: <input type="text" ng-model="user.test" ng-required="name" /><br/>
<input type="text" ng-model="user.name" ng-required="age" />
<br/>
<button type="submit">Submit</button>
</form>
Note that I put a $scope property for each input in the ng-required attribute. Now we can dynamically create that $scope property and set it to true if our data says we need to:
$scope.isRequired = function(){
$scope.requiredFields = [];
$http.get('fields.json')
.success(function(data){
$scope.requiredFields = angular.fromJson(data);
console.log($scope.requiredFields.required)
for (i = 0; i < $scope.requiredFields.required.length; i++) {
$scope[$scope.requiredFields.required[i]] = true
}
console.log($scope[$scope.requiredFields.required[0]]);
})
//$scope.requiredFields = STUFF FROM SOME REST SERVICE
}
$scope.isRequired()
So it is iterating over an array of required fields received from the server, and then dynamically creating a $scope property for each one that is required, and setting it to true. Any field that has that $scope property in it's ng-required will be required now. Anything not dynamically created will just return false, and ng-required doesn't trigger.
Original answer:
Plunker
As Pratik mentioned, ng-required only accepts a Boolean value, but we can toggle the value of that with a function.
HTML
<form>
Name: <input type="text" ng-model="user.name" ng-required="isRequired" />
<br/><button ng-click="toggle()">Required: {{isRequired}}</button>
<button type="submit">Submit</button>
</form>
code:
$scope.isRequired = true;
$scope.toggle = function() {
$scope.isRequired = !$scope.isRequired;
}
I know this is a couple of years old and so AngularJS may have changed, but the accepted answer as it stands today isn't correct. You can very easily execute a function within ng-required, as it takes an expression, which can be a function. For example:
index.html
<div ng-controller="ExampleController" class="expressions">
Expression:
<input type='text' ng-model="expr" size="80"/>
<button ng-click="addExp(expr)">Evaluate</button>
<ul>
<li ng-repeat="expr in exprs track by $index">
[ X ]
<code>{{expr}}</code> => <span ng-bind="$parent.$eval(expr)"></span>
</li>
</ul>
</div>
script.js
angular.module('expressionExample', [])
.controller('ExampleController', ['$scope', function($scope) {
var exprs = $scope.exprs = [];
$scope.expr = '3*10|currency';
$scope.addExp = function(expr) {
exprs.push(expr);
};
$scope.removeExp = function(index) {
exprs.splice(index, 1);
};
}]);
In script.js, a function addExp is defined and added to the scope, and then it's called in the ng-click directive of the a tag, which also takes an expression as its argument.
This code is taken directly from the AngularJS documentation on expressions. It doesn't use ng-require directly, but any directive that takes an expression will work the same. I have used the same syntax to use a function for ng-require.

Categories