how to implement ng-model value from another view in ionic - angularjs

I want to display ng-model value from page to input in another page
I Want display selected issue from issues page to contact page
Issue Controller
.controller('IssueCtrl', function($scope, $http) {
$http.get('api/issues').then(function(resp) {
console.log('Success', resp);
$scope.issues = resp.data;
}, function(err) {
console.error('ERR', err);
$scope.issues = err;
});
})
Contact Controller
.factory('Post', function($resource) {
return $resource('api/add_new_order',{problem: "#problem"});
})
.controller('ContactCtrl', function($scope, Post) {
// Get all posts
$scope.posts = Post.query();
// Our form data for creating a new post with ng-model
$scope.postData = {};
$scope.newPost = function() {
var post = new Post($scope.postData);
post.$save();
}
$scope.issues = {};
$scope.answer = function(){
console.log($scope.issues.name);
}
})
Issue View
<ion-list ng-repeat="item in issues">
<ion-radio ng-model="issues.name" ng-value="'{{item.issue}}'">
{{item.issue}}
</ion-radio>
</ion-list>
Contact View
<form ng-submit="newPost()">
<label class="item item-input">
<span class="input-label">Problem :</span>
<input type="text" name="problem" ng-model="postData.problem">
</label>
</form>

Your API requests should be on independent services, so they can be accessed by any controller.
As you seen to know how a factory works, I will give you an example.
.factory('IssuesService', function($http) {
var issues = [];
return {
all: function() {
return $http.get('api/issues')
.then(function(data){ // Optional callback inside service
issues = data;
});
}
}
})
.controller('ContactCtrl', function($scope, Post, IssuesService) {
...
$scope.issues = [];
IssuesService.all().then(function(data){
$scope.issues = data;
})
...
})
.controller('IssueCtrl', function($scope, $http) {
IssuesService.all()
.then(function(resp) {
console.log('Success', resp);
$scope.issues = resp.data;
}, function(err) {
console.error('ERR', err);
$scope.issues = err;
});
})

Related

How to bind data in 'value' attribute of <input tag> to NET core MVC model using angular

I’ve been playing around with Upload file - Streaming method. The original code, here:
https://github.com/aspnet/Docs/tree/master/aspnetcore/mvc/models/file-uploads/sample/FileUploadSample
However, I’m trying to get the data in the value attribute of <input value=” ”> using Angular, the idea is that I can POST the value into my MVC model instead of whatever is typed by the user (as in the original code). So, I have done this change to the input value property.
Streaming/Index.cshtml:
<div ng-app="myApp">
<div ng-controller="myCtrl">
..
<input value="#Model.name” type="text" name="Name" ng-model="name"/>
..
<button ng-click="createUser()">Create User</button>
..
</div>
</div>
#section scripts{
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="~/js/app.js"></script>
}
However, with Angular code running under app.js, the following piece of code actually fails with status code 400. This is because the passed value is “” and not the data under of value attribute of the HTML input tag.
App.js:
var User = (function () {
function User(name) {
this.name = name;
}
return User;
}());
var myApp = angular.module('myApp', []);
myApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function () {
scope.$apply(function () {
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
myApp.service('userService', ['$http', function ($http) {
this.createUser = function(user) {
var fd = new FormData();
fd.append('name', user.name);
return $http.post('/streaming/upload', fd, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined
}
});
};
}]);
myApp.controller('myCtrl', ['$scope', 'userService', function ($scope, userService) {
$scope.createUser = function () {
$scope.showUploadStatus = false;
$scope.showUploadedData = false;
var user = new User($scope.name);
userService.createUser(user).then(function (response) { // success
if (response.status == 200) {
$scope.uploadStatus = "User created sucessfully.";
$scope.uploadedData = response.data;
$scope.showUploadStatus = true;
$scope.showUploadedData = true;
$scope.errors = [];
}
},
function (response) { // failure
$scope.uploadStatus = "User creation failed with status code: " + response.status;
$scope.showUploadStatus = true;
$scope.showUploadedData = false;
$scope.errors = [];
$scope.errors = parseErrors(response);
});
};
}]);
function parseErrors(response) {
var errors = [];
for (var key in response.data) {
for (var i = 0; i < response.data[key].length; i++) {
errors.push(key + ': ' + response.data[key][i]);
}
}
return errors;
}
The solution must be a simple one, but after much research, I haven’t been able to find out how to modify it to make the data in the value=’’” attribute being passed across. This might be a stupid question but a headache for me however since I’m a total newbie regarding Angular. Please have some mercy, help.
Thanks
Use the ng-init directive to initialize the model:
<input ng-init="name= #Model.name" type="text" name="Name" ng-model="name"/>

Sharing scope data in controller

My spring mvc controller returns an object.
My scenario is:
On click of a button from one page say sample1.html load a new page say sample2.html in the form of a table.
In sample1.html with button1 and controller1--> after clicking button1-->I have the object(lets say I got it from backend) obtained in controller1.
But the same object should be used to display a table in sample2.html
How can we use this object which is in controller1 in sample2.html?
You can use a service to store the data, and inject it in your controllers. Then, when the value is updated, you can use a broadcast event to share it.
Here is a few example:
HTML view
<div ng-controller="ControllerOne">
CtrlOne <input ng-model="message">
<button ng-click="handleClick(message);">LOG</button>
</div>
<div ng-controller="ControllerTwo">
CtrlTwo <input ng-model="message">
</div>
Controllers
function ControllerOne($scope, sharedService) {
$scope.handleClick = function(msg) {
sharedService.prepForBroadcast(msg);
};
}
function ControllerTwo($scope, sharedService) {
$scope.$on('handleBroadcast', function() {
$scope.message = sharedService.message;
});
}
Service
myModule.factory('mySharedService', function($rootScope) {
var sharedService = {};
sharedService.message = '';
sharedService.prepForBroadcast = function(msg) {
this.message = msg;
this.broadcastItem();
};
sharedService.broadcastItem = function() {
$rootScope.$broadcast('handleBroadcast');
};
return sharedService;
});
JSFiddle demo
you can use factory to share data between controllers
<div ng-controller="CtrlOne">
<button ng-click="submit()">submit</button>
</div>
<div ng-controller="CtrlTwo">
{{obj}}
</div>
.controller('CtrlOne', function($scope, sampleFactory) {
$scope.sampleObj = {
'name': 'riz'
}; //object u get from the backend
$scope.submit = function() {
sampleFactory.setObj($scope.sampleObj);
}
})
.controller('CtrlTwo', function($scope, sampleFactory) {
$scope.obj = sampleFactory.getObj();
})
.factory('sampleFactory', function() {
var obj = {};
return {
setObj: function(_obj) {
obj = _obj;
},
getObj: function() {
return obj;
}
}
})

How to save data values from form in angularjs using fat free framework

I am trying to save data in sql using fat free framework. i used front end in angularjs. i send data using angular ng-submit button. ajax Post data but not get in fat free please solve this problem. i am new in fat free.
here is my html code:
<form id="userRegister" name="registration" ng-submit="register1(formData)" ng-controller="Ctrl1">
<div class="sf-steps-form sf-radius">
<div class="sf_columns column_3">
<input ng-model="formData.email" id="email" type="email" name="email" placeholder="Email*" data-required="true" >
</div>
<div class="sf_columns column_3">
<input ng-model="formData.password" id="password" type="password" name="password" placeholder="Secret Word*" data-required="true" >
</div>
</div>
<button type="submit" id="sf-next" class="sf-button">Save</button>
</form>
here is my app.js code:
sampleApp.controller("Ctrl1", function($scope, $http) {
$scope.formData = {};
$scope.register1 = function() {
console.log($scope.formData);
$http({
method : 'POST',
url : 'addstep',
data : $scope.formData,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) {
if (data.errors) {
$scope.errorEmail = data.errors.email;
$scope.errorPassword = data.errors.password;
} else {
$scope.message = data.message;
}
});
};
});
here is my idex.php fat free framework code:
$f3->route('GET|POST /addstep',
function($f3) {
//print_r($f3);
$users = new DB\SQL\Mapper($f3->get('DB'),'user');
$users->copyFrom('POST');
$users->save();
$f3->set('content','step1.htm');
echo View::instance()->render('layout.htm');
}
);
The ajax post data properly but not save in db please help.
Check $f3->get('BODY');
You might need to json_decode;
Most likely the data is sent via PUT
I actually just dealt with this on an application using f3 and angular. If you haven't figured it out I have been pretty successful with this:
I have an angular $http service:
angular.module('myApp')
.service('apiConnector', function apiConnector($http) {
var apiBase = '';
var obj = {};
obj.get = function(q) {
return $http.get(apiBase + q).then(function(results) {
return results.data;
});
};
obj.post = function(q, object) {
return $http.post(apiBase + q, object).then(function(results) {
return results.data;
});
};
obj.put = function(q, object) {
return $http.put(apiBase + q, object).then(function(results) {
return results.data;
});
};
obj.delete = function(q) {
return $http.delete(apiBase + q).then(function(results) {
return results.data;
});
};
return obj;
});
Then I use this service in my angular controllers like so:
angular.module('myApp')
.controller('homeController',function($scope, $state, $stateParams, $timeout, apiConnector){
$scope.user = {};
apiConnector.get('/api/users/'+$stateParams.id)
.then(function(res){
if (res.success) {
$scope.user = res.data;
}
},function(err){
console.log(err);
});
$scope.updateUser = function(user) {
apiConnector.post('/api/users/'+$stateParams.id,user)
.then(function(res){
if (res.success) {
alert('updated');
}
}, function(err){
console.log(err);
});
};
});
Lastly the f3 controller. I am using [maps] for my routes to get a truly restful interface, and my routes use an #id param. I collect data like so:
class Item {
function get($app,$params) {
$id = $params['id'];
$user = new \Models\User();
$user->load(array('id = ?',$id));
echo json_encode($user->cast());
}
function post($app,$params) {
$POST = json_decode(file_get_contents('php://input'));
$id = $params['id'];
$user = new \Models\User();
$user->load(array('id = ?',$id));
$user->copyfrom($POST);
$user->touch('created');
$user->save();
echo json_encode(array('message' => 'Successfully updated user!'));
}
function put() {}
function delete() {}
}
Hope that helps!

MEAN with Jade template form submit GET instead of POST

So, earlier today I had a working form that could post and delete restaurants documents to a mongodb collection. Everything was working fine, but then I decided to try and load the form into a div instead of redirect to a new page. Doing so produced a different result when I tried to submit my restaurant form. Originally it would call $scope.add() in my restaurantsController, but now it is sending a GET request with form data to /restaurants instead of a POST to /api/restaurants. I'm looking for some insight as to what I did to change the behavior. Although it is loading the form when I click on my restaurant anchor tag, it is not loading the restaurants from the database.
Here is the jade and js for the menu anchors:
menu.js
app.controller("menu", ["$scope", "$http", function ($scope, $http) {
$scope.home = function () {
$("#content").html("");
};
$scope.restaurants = function () {
$http.get('/restaurants').
success(function(data, status, headers, config){
$("#main_content").html(data);
}).
error(function(data, status, headers, config){
});
};
}]);
nav.jade
mixin link(name, fn)
li
a.btn(ng-click=fn)= name
nav.navbar.navbar-inverse.navbar-fixed-top(role='navigation')
.container
.navbar-header
button.navbar-toggle.collapsed(type='button', data- toggle='collapse', data-target='#navbar', aria-expanded='false', aria- controls='navbar')
span.sr-only Toggle navigation
span.icon-bar
span.icon-bar
span.icon-bar
a.navbar-brand(href='/') Food App
#navbar.navbar-collapse.collapse
ul.nav.navbar-nav(ng-controller="menu")
+link("Home", "home()")
+link("Restaurants", "restaurants()")
And here is the form:
form(name="NewRestaurant" ng-submit="$event.preventDefault();add()")
.row
.form-group
input.form-control(type="text", name="name" placeholder="Name", ng-model="name" required)
.row
.form-group
input.form-control(type="text", name="address" placeholder="Address", ng-model="address" required)
.row
.form-group.col-md-6
-for(var i = 0; i <= 5; i++){
input(name="rating" type="radio", value=i, ng-model="rating" required)
=i
-}
.form-group.col-md-6
button.success(type="submit") Submit
and the controller...
app.controller("restaurants", ["$scope", "$resource", function ($scope, $resource) {
var Restaurant = $resource('/api/restaurants/:id');
var clearForm = function () {
$scope.name = '';
$scope.address = '';
$scope.rating = null;
}
clearForm();
var validRestaurant = function () {
if($scope.name !== '' && $scope.address !== '' && $scope.rating !== null)
return true;
else{
toastr.error("Please fill in all required form fields.");
return false;
}
}
$scope.query = function(){
Restaurant.query(function (results) {
$scope.restaurants = results;
});
};
$scope.add = function () {
alert("got here!");
if(validRestaurant()){
var restaurant = new Restaurant();
restaurant.name = $scope.name;
restaurant.address = $scope.address;
restaurant.rating = $scope.rating;
alert(restaurant);
Restaurant.save(restaurant, function (result) {
$scope.restaurants.push(result);
toastr.success("Saved " + $scope.name + ".")
clearForm();
});
}
};
$scope.update = function (id) {
};
$scope.remove = function (id) {
console.log(id);
Restaurant.delete({id: id}, function (err) {
console.log(err);
$scope.query();
});
};
$scope.query();
}]);
edit: Now that I am typing this up, I am wondering, maybe angular doesn't recognize the form and doesn't create a $scope for it because it gets loaded after the page loads...?

How can I use the exact same array from one service in two controllers?

I have this code:
controller:
function deleteRootCategory(){
$scope.rootCategories[0] = '';
}
function getCategories(){
categoryService.getCategories().then(function(data){
$scope.rootCategories = data[0];
$scope.subCategories = data[1];
$scope.titles = data[2];
});
}
getCategories();
service:
var getCategories = function(){
var deferred = $q.defer();
$http({
method:"GET",
url:"wikiArticles/categories"
}).then(function(result){
deferred.resolve(result);
});
}
return deferred.promise;
}
html:
<div ng-controller="controller">
<div ng-repeat="root in rootCategories"> {{root}} </div>
<div ng-repeat="sub in subCategories"> {{sub}} </div>
<div ng-repeat="title in titles">{{title}}</div>
</div>
html2:
<div ng-controller="controller">
<div ng-include src="html"></div>
<button ng-click="deleteRootCategory()">Del</button>
</div>
When I click the deleteRootCategory-button the array $scope.rootCategories is updated, but the view won't ever change.
What am I missing?
Thanks
You will probably want to have a broadcast event set up when the value is changed in the service. Something like this.
.service("Data", function($http, $rootScope) {
var this_ = this,
data;
$http.get('wikiArticles/categories', function(response) {
this_.set(response.data);
}
this.get = function() {
return data;
}
this.set = function(data_) {
data = data_;
$rootScope.$broadcast('event:data-change');
}
});
Have both controllers waiting for the event, and using the set to make any changes to the array.
$rootScope.$on('event:data-change', function() {
$scope.data = Data.get();
}
$scope.update = function(d) {
Data.set(d);
}

Resources