How to pass value from AngluarJS to MVC Controller - angularjs

I am working with AngularJS and I am trying to pass a value from the Angular into the Controller. This is what my AngularJS Script File looks like:
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
{
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
// add a zero in front of numbers<10
m = checkTime(m);
s = checkTime(s);
return (h + ":" + m + ":" + s);
t = setTimeout('startTime()', 500);
}
$scope.name = startTime();
}
});
</script>
So from that I am able to get the time through calling $scope.name. But I want to pass that variable into the controller. The way I was thinking of doing it was to pass it in an Html.BeginForm as a parameter but that's not working. This is my BeginForm:
<div ng-app="myApp" ng-controller="myCtrl">
#using (Html.BeginForm("Bob", "Home", new { Time = ng-model="name" },
FormMethod.Post, null))
{
<p>Name:</p> <input style="color:black;" ng-model="name">
<h1 style="color:black;">You entered: {{name}}</h1>
<button type="submit" style="color:black;">Submit</button>
}
</div>
Right now I have the input box there just so I could make sure that it's passing the right value, and it is. But in the BeginForm it's not allowing Time to equal the value being passed from the AngularJS. How would I be able to pass that value to the Controller?

You could pass it as a hidden field:
#using (Html.BeginForm("Bob", "Home", FormMethod.Post))
{
<input name="time" type="hidden" ng-value="name" />
<button type="submit" style="color:black;">Submit</button>
}

Related

Adding Text Box to Angular Form

I'm trying to dynamically add a textbox to an Angular form. I'm using ng-repeat and I can add the text box easily by just pushing, an empty string to the array. It will add another textbox, the problem is that ng-model is not syncing the data, and when text is added it remains an empty string.
The text boxes that get created from the initial array sync just fine, it's just the newly added text boxes that are not working.
I've been looking around and one suggestion I saw was to always use a "." when using ng-model, but that didn't work for me.
<div ng-repeat="text in image.text track by $index">
<md-input-container class="md-block" novalidate>
<label>Text {{$index + 1}}:</label>
<textarea md-maxlength="2500" md-midlength="1" required md-no-asterisk name="text"
placeholder="{{text}}"
ng-model="text"></textarea>
</md-input-container>
</div>
Controller:
(function () {
'use strict';
angular
.module('app.article')
.controller('ArticleEditController', ArticleEditController);
ArticleEditController.$inject= ['articleEditDataService', '$routeParams', '$log'];
function ArticleEditController(articleEditDataService, $routeParams, $log) {
var vm = this;
 var site = $routeParams.site;
var articleName = $routeParams.article;
var articleRevision_id = $routeParams.revision_id;
vm.data = {};
vm.addNewText = addNewText;
vm.removeText = removeText;
vm.saveArticle = saveArticle;
vm.numMessage = 1;
activate();
function activate(){
getArticle();
}
function getArticle(){
var data = articleEditDataService.getArticle(site, articleName, articleRevision_id);
data.then(function successResponse(res) {
vm.data = res.results.data;
}, function errorResponse (res) {
console.log(res);
});
}
function saveArticle(){
var article = articleEditDataService.postArticle(vm.data, site, articleName, articleRevision_id);
console.log(vm.data);
article
.then(updateArticleSuccess)
.catch(updateArticleError);
}
function updateArticleSuccess(message){
$log.info(message);
}
function updateArticleError(errorMessage){
$log.error(errorMessage);
}
function addNewText (index, key) {
vm.data.content.image_sets[key].text.push("");
}
function removeText (index, key) {
if(vm.data.content.image_sets[key].text.length > 1){
vm.data.content.image_sets[key].text.pop();
}
}
};
})();
initialize the model variable within your controller as an empty object.
then within your text input your ng-model="model[$index]".

How to get value of ng-change ionic/angular?

I m new in angularJS:
When I change the value of my input, in my console I don t have the new value.
How can I get the new value of my input when I change it?
controller.js:
$scope.nam = guillaume;
$scope.firstchange = function(){
$scope.displayed = {'display':'block'};
console.log($scope.nam);
};
home.html:
<input ng-change="firstchange()" ng-model="nam" class="param-right"></input><p>Prénom</p>
You have to pass the model as a parameter to your handler.
controller.js
$scope.nam = guillaume;
$scope.firstchange = function(nam){
$scope.displayed = {'display':'block'};
console.log(nam);
};
home.html
<input ng-change="firstchange(nam)" ng-model="nam" class="param-right"></input><p>Prénom</p>

Get value from HTML page to angularJS file

I tried to get the HTML page value to angularJS function , The below steps are which i tried.
HTML page :
<label class="item-input item-stacked-label">
<span class="input-label cont_det_label">First Name</span>
<p class="contact_display" id="txtFirstName" ng-model="testName">Satya</p>
</label>
angularJS Page :
.controller('SocialNetworkCtrl', ['$scope','$http','$state','ContactsService','$ionicNavBarDelegate','$ionicLoading','$ionicPopup',function($scope, $http, $state, ContactsService, $ionicNavBarDelegate, $ionicLoading,$ionicPopup) {
$scope.showUserProfile = function() {
$state.go("linkedin");
var firstname = (document.getElementById("txtFirstName").value);
}
}])
So I need var firstname = Satya ?? Is it correct way please guide me to access this value .
var firstName = $scope.testName
<input ng-model="testName" />
testName is the ng-model name that you have give. It will be automatically binded to your controller. No need the get the value using document.getElementById
Wrong usage , why ng-model in <p> tag??
Update
Change your fiddle with the following code, it will work. Also make sure framework is selected properly (as in the image)
<div ng-app ng-controller="testController">
<input ng-model="testDataName" ng-change="check()" /> {{testDataName}}
After ng-change : {{checkName}}
</div>
function testController($scope) {
$scope.testDataName="Dummy Name";
$scope.check = function () {
$scope.checkName=$scope.testDataName;
console.log($scope.checkName);
};
}
its a text node, you will require .innerHTML or '.innerText', .value is for form inputs
var firstname = (document.getElementById("txtFirstName").innerHTML);
and don't use ng-model on a p element, change it to like this
<p class="contact_display" id="txtFirstName">{{testName}}</p>
just use $scope.testName to get the value, no need for firstname = (document.getElementById("txtFirstName").innerHTML); querying DOM for value is jQuery style, use angular the $scope for 2 way bindings
Read more at official doc
Update here is updated function on loginCtrl
.controller('loginCtrl', ['$scope', function ($scope) {
$scope.testNameData = 'Satya';
$scope.doLogin = function() {
alert($scope.testNameData);
};
}])
If you really want to go jQuery way here is what you can do, its not recommended, you should use angular directive to do DOM manipulation
$scope.showUserPro = function() {
$ionicLoading.show();
// Here i need the value of <p tag>
var name = document.getElementById("txtFirstName"),
firstNameFromHtmlPtag = name.innerText;
console.log(firstNameFromHtmlPtag, 'Doing API Call 1');
}

angularjs form, input value changed programmatic(by code) not submitted to controller

my problem is that after change input value by code or any plugin new value not submitted to controller and old value of property is accessible.
but if change input value by typing new value is available! only by typing!
template :
<input class="form-control" id="ng-taskLineBackColor"
type="text" ng-model="data.preference.lineBackColor"/>
<input type="submit" ng-click="update()" class="btn btn-primary" value="save"/>
controller :
.controller('taskCtrl', ['$scope', function ($scope) {
$scope.getRef = function () {
return //any code
};
$scope.save = function () {
var newValue = $scope.data.preference.lineBackColor;
//!!!-->newValue Contain old Value
};
}])
Any code which changes the value of ng-taskLineBackColor needs to trigger a special event called "input". This will notify AngularJS
$(function() {
$('#ng-taskLineBackColor').val('new value').trigger('input');
});
To do this only with jQlite and without jQuery try:
angular.element(document.querySelector('#ng-taskLineBackColor')).triggerHand‌​ler('input')
And here's the API you have available on an angular.element-wrapped HTML element:
https://docs.angularjs.org/api/ng/function/angular.element
I create working JSfiddle for your case.
JSfiddle
<input class="form-control" id="ng-taskLineBackColor"
type="text" ng-model="data.preference.lineBackColor"/>
<input type="submit" ng-click="update()" class="btn btn-primary" value="save"/>
I renamed function "save", declared in controller on "update".
UPDATE:
function MyCtrl($scope) {
$scope.update = function () {
var value = $scope.data.preference.lineBackColor;
alert("Typing value = '" + value + "'");
$scope.data.preference.lineBackColor = "Value from code";
var newValue = $scope.data.preference.lineBackColor;
alert("Typing value = '" + newValue + "'");
};
}

Another issue after AngularFire 0.5.0 update - calculation returns NaN

I'm more and more disappointed with the angularFire 0.5.0, because nothing works correctly anymore. After I was able to fix the remove of a single item with help of you, I ran into another issue.
Each single item consists of a date, description and price. Before I updated, I was able to calculate the total of all prices and return it on the page. Now it just says NaN or Null. I was already trying to figure out why, but both values (earning.price, $scope.totalEarning) in the calculation are numbers. I don't get it. Does the new angular fire do anything? I'm trying to fix it since a while and just can't. I would be really, if somebody could figure it out. Probably I'm just not seeing it and it's a pretty dumb issue.
See it on plunkr: http://embed.plnkr.co/jb1iWOcjcm0alFchmzOH/preview
Here is the code:
$scope.addEarning = function() {
$scope.earnings.$add({date:$scope.FormEarningDate, description:$scope.FormEarningDescription, price:$scope.FormEarningPrice});
$scope.FormEarningDate = '';
$scope.FormEarningDescription = '';
$scope.FormEarningPrice = '';
$scope.updateEarning();
}
$scope.updateEarning = function() {
$scope.totalEarning = 0;
angular.forEach($scope.earnings, function (earning) {
price = parseFloat(earning.price)
$scope.totalEarning += price;
$log.log(typeof $scope.totalEarning);
})
$scope.totalBalance = $scope.totalEarning - $scope.totalCost;
}
And the html:
<form for="Profit" class="form-inline" style="margin-bottom: 20px" ng-submit="addEarning()">
<div class="form-group">
<div class="col-sm-3">
<input type="date" name="idate" ng-model="FormEarningDate" class="form-control" id="idate" placeholder="Date">
</div>
<div class="col-sm-5">
<input type="text" name="idesc" ng-model="FormEarningDescription" required class="form-control" id="idesc" placeholder="Description">
</div>
<div class="col-sm-2">
<input type="text" name="iprice" ng-model="FormEarningPrice" required class="form-control" id="iprice" placeholder="Amount">
</div>
</div>
<tr ng-repeat="earning in earnings | orderByPriority | orderBy : 'date'">
<td>{{earning.date}}</td>
<td>{{earning.description}}</td>
<td>{{earning.price}} €</td>
<td><button class="btn btn-danger" ng-click="earnings.$remove(earning.$id)">Löschen</button></td>
</tr>
<tr>
<td colspan="2"></td>
<td><strong>Total:</strong> {{totalEarning}} €</td>
<td></td>
</tr>
Updated Answer
There are several things you are doing incorrectly. As stated in my original answer, you need to iterate over the keys from Firebase, not the firebase object itself. Additionally, you need to ensure all updates happen after Firebase has updated (via an $on('change', ...) event handler) and within the AngularJS lifecycle (accomplished below using $timeout).
var app = angular.module('balance', ['firebase']);
app.controller('BalanceCtrl', function($scope, $log, $http, $timeout, $firebase) {
$scope.earnings = $firebase(new Firebase('https://dgdemo.firebaseio.com/Earnings'));
$scope.totalBalance = 'Nothing yet.';
$scope.totalEarning = 0;
$scope.totalCost = 0;
$scope.updateEarning = function() {
$scope.totalEarning = 0;
angular.forEach($scope.earnings.$getIndex(), function (id) {
var earning = $scope.earnings[id];
$scope.totalEarning += parseFloat(earning.price);
});
$scope.totalBalance = $scope.totalEarning - $scope.totalCost;
};
// Ensure any call to updateCallback will execute within the AngularJS lifecycle.
var updateCallback = angular.bind(null, $timeout, $scope.updateEarning);
$scope.addEarning = function() {
var earning = $scope.earnings.$add({
date: $scope.FormEarningDate,
description: $scope.FormEarningDescription,
price: $scope.FormEarningPrice
});
$scope.FormEarningDate = '';
$scope.FormEarningDescription = '';
$scope.FormEarningPrice = '';
};
$scope.earnings.$on('change', updateCallback);
});
Original Answer
This is because angular.forEach is iterating over all properties of the $scope.earnings object (which is a Firebase object). What you want to do is iterate over the individual items.
$scope.updateEarning = function() {
$scope.totalEarning = 0;
angular.forEach($scope.earnings.$getIndex(), function (id) {
var earning = $scope.earnings[id];
$scope.totalEarning += parseFloat(earning.price);
});
$scope.totalBalance = $scope.totalEarning - $scope.totalCost;
}

Resources