View:
<ul ng-repeat="x in posts.post">
{{x.name}} {{x._id}} {{x.post}} {{x.user_id}}
<br>
<ul ng-repeat="y in x.comment">
{{y.comment}}
</ul>
<input type="text" style="display: none;" ng-model='new_comment.userId' value={{users2.id}} name="userId" >
<input type="text" style="display: none;" ng-model='new_comment.name' value={{users2.name}} name="userName" >
<textarea ng-model='new_comment.comment' name="comment" rows="4" cols="50">
</textarea>
<br>
<input type="submit" value="Post Comment!" ng-click="addComment(x._id, new_comment)">
</ul>
Controller:
UserFactory.getUser(function (data) {
$scope.users2 = data;
});
Factory:
factory.getUser = function(callback) {
$http.get("/user").success(function(output) {
users2 = output;
callback(users2);
});
};
I am trying to pass the hidden values of users2.id and users2.name from the controller/factory into a form. I tried ng-init, ng-value as well as input type="hidden", but none works.
So this is what I did to get it working:
View:
<form>
<textarea ng-model='new_comment.comment' name="comment" rows="4" cols="50">
</textarea>
<br>
<input type="submit" value="Post Comment!" ng-click="addComment(x._id, new_comment, users2.name, users2._id)">
</form>
Controller:
$scope.addComment = function(id, comment, userName, userId) {
var commentValue = comment.comment;
var newComment = {comment: commentValue, name: userName, userId: userId};
postFactory.addComment(id, newComment, function () {
postFactory.getComment(function (data) {
$scope.comments = data;
});
$scope.new_comment = {};
});
};
Try this
<input type="hidden" ng-model='new_comment.userId' value="{{users2.id}}" name="userId" >
And while you are changing things
UserFactory.getUser
.then(function (data) {
$scope.users2 = data;
});
with
factory.getUser = function() {
return $http.get("/user");
};
as $http returns a promise
Two way binding wouldn't work with hidden element, so I'd use ng-value to set the value of type="hidden" element
<input type="hidden" ng-value='new_comment.userId' name="userId"/>
<input type="hidden" ng-value='new_comment.name' name="userName"/>
Do something like this, return the promise.
factory.getUser = function(callback) {
return $http.get("/user")
};
Controller:
UserFactory.getUser().success(function(output) {
$scope.users2 = output.data;
});
Related
I have a progress bar I want to show after I click a button.
I set my variable to true on click, yet it's not working.
The ng-show in question is on the bottom of the html, and the button i click is on a different html page but i didn't include because it uses the successOnClick function in this same controller. I console logged the isEmailing variable inside the onclick and it is assigned true. Doesn't work for ng-if either
What gives?
module.exports = app => {
app.controller('ContactController', ($scope, $http) => {
$scope.isEmailing = false;
$scope.email = (e) => {
$scope.isEmailing = true;
const requestBody = {};
const id = e.target.id;
requestBody.name = document.getElementById(`${id}-name`).value;
requestBody.email = document.getElementById(`${id}-email`).value;
requestBody.subject = document.getElementById(`${id}-subject`).value;
requestBody.body = document.getElementById(`${id}-body`).value;
$http.post('/email', JSON.stringify(requestBody), {
'Content-Type': 'application/json'
})
.then(res => {
console.log('Success!');
document.getElementById(`${id}-name`).value = '';
document.getElementById(`${id}-email`).value = '';
document.getElementById(`${id}-subject`).value = '';
document.getElementById(`${id}-body`).value = '';
$scope.isEmailing = false;
})
.catch(err => {
console.log('Error!');
$scope.isEmailing = false;
})
}
$scope.successOnClick = () => {
$scope.isEmailing = true;
}
})
}
<footer class="footer" ng-controller="ContactController">
<div class="footer__block social-media-container">
<div class="social-media">
<img src="http://i.imgur.com/bVqv5Kk.png" alt="fb-icon">
<img src="http://i.imgur.com/sJWiCHV.png" alt="twitter-icon">
<img src="http://i.imgur.com/o7yTVyL.png" alt="insta-icon">
</div>
</div>
<div class="footer__block">
<form class="footer__form" ng-submit="email($event)" id="footer">
<textarea placeholder="Message" id="footer-body" required></textarea>
<input type="text" placeholder="Name" id="footer-name" required>
<input type="email" placeholder="Email" id="footer-email" required>
<input type="text" placeholder="Subject" id="footer-subject" required>
<input type="submit" placeholder="Email">
</form>
</div>
<div class="footer__block mailing-list">
<span>Join our Mailing List!</span>
<form>
<input type="email" placeholder="Email" required>
<input type="submit">
</form>
</div>
<!-- <div class="grey-screen">
<div class="success">
<h1>Success!</h1>
</div>
</div> -->
<div class="progress-bar" ng-show="isEmailing">
</div>
</footer>
If you have several controller of same type it is not mean, that they all are same the instance. AngularJS creates controllers not via singleton pattern. You should synchronize them by yourself by means of events:
angular.module('app', [])
.controller('MyController', ['$scope', '$rootScope', function($scope, $rootScope) {
$rootScope.$on('Changed', function(event, data){
$scope.isEmailing = data;
})
$scope.successOnClick = function(){
$scope.$emit('Changed', !$scope.isEmailing);
}
}]);
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="MyController">
<h3 ng-style="{'background-color' : isEmailing ? 'red' : 'white'}">First controller</h3>
<input type='button' ng-click='successOnClick()' value='Change color'/>
</div>
<div ng-controller="MyController">
<h3 ng-style="{'background-color' : isEmailing ? 'red' : 'white'}">Second controller</h3>
<input type='button' ng-click='successOnClick()' value='Change color'/>
</div>
</div>
If one controller located inside another you can try to use $scope.$parent.isEmailing(where .$parent can be typed several times, depending on nesting level), but it is very uncomfortable. If your controllers located at different routes, you should pass data from one controler to another via route parameters or custom AngularJS service or $rootScope.
<input type="text" class="form-control" placeholder="Service Number" id="service_num" name="service_num" ng-model="service_num" ng-blur="GetUfdreportdata()">
<span>Details</span>
<label>
<input type="checkbox" class="detailcheckbok" id="deatilsmanual_0" name="deatailsmanual" ng-model="deatilsmanual_0" value="0" checked/> Manual </label>
<label>
<input type="checkbox" class="detailcheckbok" id="deatilsmanual_1" name="deatailsmanual" ng-model="deatilsmanual_1" value="1" /> Auto </label>
<input type="button" value="Submit" ng-click="myfunction()" />
app.controller("cap", function($scope, $http, $mdDialog) {
$scope.myfunction = function() {
$http.post("save_report.php", {
}
}
$scope.GetUfdreportdata = function() {
$http({
method: "GET",
url: "api/api.php",
params: {
service_num: $scope.service_num
}
}).success(function(data) {}
});
Try the following code to store the 0,1 values based on checkbox behavior.
<script>
angular.module('checkboxExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.checkboxModel = { value1 : 1, value2 : 1 };
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
<label>Value1:
<input type="checkbox" ng-model="checkboxModel.value1"
ng-true-value="1" ng-false-value="0">
</label><br/>
<label>Value2:
<input type="checkbox" ng-model="checkboxModel.value2"
ng-true-value="1" ng-false-value="0">
</label><br/>
<tt>value1 = {{checkboxModel.value1}}</tt><br/>
<tt>value2 = {{checkboxModel.value2}}</tt><br/>
</form>
I'm creating a dependency dropdown from JSON(country, city). Based on country selection city will populate in second dropdown. If I get the value of country it return object with city list.
please wait to get country dropdown value from github raw.
var app = angular.module('myApp',[])
app.controller('dropdown', function($scope, $http){
$scope.istrue = true;
$scope.userInfo = [];
$http.get('https://raw.githubusercontent.com/David-Haim/CountriesToCitiesJSON/master/countriesToCities.json').then(function(response){
$scope.countriesToCities = response.data;
//console.log($scope.countriesToCities)
},function(response){
console.log(response.status);
});
$scope.populateCities = function() {
$scope.istrue = false;
//console.log($scope);
$scope.cityArray = $scope.users.country;
}
$scope.selectedCity = function(){
console.log($scope.city)
}
$scope.pushInArray = function() {
var user = angular.copy($scope.users);
$scope.userInfo.push(user);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="dropdown">
<input type="text" name="name" ng-model="users.name" placeholder="Name">
<input type="text" name="email" ng-model="users.email" placeholder="Email">
<input type="text" name="phoneNo" ng-model="users.phoneNo" placeholder="phone Number">
<select ng-model="users.country" ng-change='populateCities()' ng-options="x for (x, y) in countriesToCities"></select>
<select ng-hide="istrue" ng-model="users.city" ng-change='selectedCity()' ng-options="x for x in cityArray"></select>
<button ng-click="pushInArray()">Add</button>
<pre>{{userInfo}}</pre>
</div>
How to get the value of country?
Working snippet with modified $scope.populateCities(), $scope.user = {} object and ng-options to select correct country.
var app = angular.module('myApp',[])
app.controller('dropdown', function($scope, $http){
$scope.istrue = true;
$scope.userInfo = [];
$scope.user = {};
$http.get('https://raw.githubusercontent.com/David-Haim/CountriesToCitiesJSON/master/countriesToCities.json').then(function(response){
$scope.countriesToCities = response.data;
//console.log($scope.countriesToCities)
},function(response){
console.log(response.status);
});
$scope.populateCities = function() {
$scope.istrue = false;
angular.forEach($scope.countriesToCities, function(values, key) {
if($scope.user.country == key) {
$scope.cityArray = values;
}
});
}
$scope.pushInArray = function() {
var user = angular.copy($scope.user);
$scope.userInfo.push(user);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="dropdown">
<input type="text" name="name" ng-model="users.name" placeholder="Name">
<input type="text" name="name" ng-model="user.name" placeholder="Name">
<input type="text" name="email" ng-model="user.email" placeholder="Email">
<input type="text" name="phoneNo" ng-model="user.phoneNo" placeholder="phone Number">
<select ng-model="user.country" ng-change='populateCities()' ng-options="country as country for (country, cities) in countriesToCities"></select>
<select ng-hide="istrue" ng-model="user.city" ng-change='selectedCity()' ng-options="x for x in cityArray"></select>
<button ng-click="pushInArray()">Add</button>
<pre>{{userInfo}}</pre>
</div>
I am Getting null value in action method when i am pass data from angular js to action method. data is coming up to $scope.custmodel and i debug and see it hit to the AddCutomer method but data is null. can anyone help me to fix this issue
Admin.js code
var app = angular.module("adminmdl", [])
app.controller("admincontroller", function ($scope,AdminService) {
$scope.Action = 'Add';
$scope.data = {
cus_code: '',
cus_name: ''
}
$scope.savecu = function () {
AdminService.saveCustomerDdetails($scope.cusmodel).then(function (data) {
if (data != null) {
alert('Insert successfully');
} else {
alert('error in inerting data');
}
});
}
})
.factory("AdminService", function ($http) {
var fact = {};
fact.saveCustomerDdetails = function (d) {
return $http({
url: '/Admin/AddCutomer',
method: 'POST',
data: JSON.stringify(d),
headers: { 'content-type': 'application/json' }
});
};
return fact;
});
ASP MVC Method
[HttpPost]
public JsonResult AddCutomer(Customer customer) {
te.Customers.Add(customer);
te.SaveChanges();
string message = "Success";
return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
html code
<form class="form-horizontal" method="post" action="#" name="basic_validate" id="basic_validate" novalidate="novalidate">
<div class="control-group">
<label class="control-label">Customer Code</label>
<div class="controls">
<input type="text" ng-model="cusmodel.Customercode" name="required" id="required" >
</div>
</div>
<div class="control-group">
<label class="control-label">Customer Name</label>
<div class="controls">
<input type="text" ng-model="cusmodel.Customername" name="name" id="name" >
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" value="Save" ng-click="savecu()" class="btn btn-success">
<input type="submit" value="Clear" class="btn btn-success" />
</div>
</div>
add [FromBody] attribute to the controller as shown below
public JsonResult AddCutomer([FromBody] Customer customer)
HTML:
<div ng-controller="TestController" >
<form name="test_form" ng-submit="submit()">
<input type="text" name="some_name" ng-model="form_data.some_name" required>
<ng-form ng-repeat="key in keys" name="keyForm">
<input type="text" name="data_input" ng-model="form_data.data_input" required>
</ng-form>
<a ng-click="addKey()">NEW KEY</a>
</form>
</div>
JS:
app.controller('TestController', function TestController($scope){
$scope.keys = [];
$scope.addKey = function() {
$scope.keys.push({});
}
$scope.submit = function() {
console.log($scope);
}
});
In submit function I can get the value of "some_name" input:
$scope.submit = function() {
console.log($scope.form_data.some_name);
}
But I can't get the values of "data_input" inputs (they are inside ngform tag). How to do that?
(ngform tag is using for ability to validate each new added input separately)
Each input inside the ng-repeat needs its own unique ng-model property -- they all can't use form_data.data_input. Here is one way to solve your problem:
<ng-form ng-repeat="key in keys" name="keyForm">
<input type="text" name="data_input" ng-model="key.data" required>
</ng-form>
$scope.addKey = function () {
$scope.keys.push({ data: ''});
}
Fiddle.
See also https://stackoverflow.com/a/14379763/215945