My setup is NodeJS, MongoDB, and Angular. I'm currently trying to add POSTing capability to my test code but can't quite wrap my head around it. Currently I can pull data from the DB and I threw together a quick and dirty form/factory based on a number of examples I've seen to try to get the POST function working.
The problem I'm running into is actually getting the values to be added to the DB. When I submit the form, a new ObjectID is created in the DB with a "_v" field and a value of 0. So I know the POST is at least being sent to the DB, but the values I want are not. I'm sure I'm doing something stupid and any help is greatly appreciated.
Here is my controller/factory setup: (I named the POST factory "taco" so it would stand out. Also because they're delicious.)
angular.module('app', ['ngRoute'])
.factory('Users', ['$http', function($http) {
return $http.get('/users');
}])
.factory('taco', ['$http', function($http) {
return $http.post('/users');
}])
.controller('UserController', ['$scope', 'Users', function($scope, Users) {
Users.success(function(data) {
$scope.users = data;
}).error(function(data, error) {
console.log(error);
$scope.users = [];
});
}])
.controller('ExampleController', ['$scope', 'taco', function($scope, taco) {
$scope.submit = function() {
if ($scope.users.name) {
$scope.name.post(this.name);
$scope.name = '';
}
};
}]);
Here is my form:
<div>
<form ng-submit="submit()" ng-controller="ExampleController">
Enter the things:<br/>
<input type="text" ng-model="name" name="user.name" placeholder="name" /><br/>
<input type="text" ng-model="emp_id" name="user.emp_id" placeholder="EID" /><br/>
<input type="text" ng-model="loc" name="user.loc" placeholder="location" /><br/>
<input type="submit" id="submit" value="Submit" />
</form>
</div>
To post using the $http service you can do:
angular.module('myApp')
.controller('MyController', function($scope, $http) {
$http.post('/destination', {my: 'data'});
});
You're not sending any data in your POST request. The taco service just executes a $http.post call and returns the promise.
Please look at the $http service documents: https://docs.angularjs.org/api/ng/service/$http
I would define a function submit that would send the data once a user clicks on submit:
$scope.submit = function() {
$http.post('/destination', {my: 'data'});
}
Related
I am trying to submit a form using angular1 but when I click submit I can't see the call being made to /create in Network tab of Chrome Dev tool.
My app.js is:
app.controller('MyCtrl', ['$scope', 'Upload', '$timeout', function ($scope, Upload, $http, $timeout) {
$scope.loaderHidden = true;
$scope.csvurls = function() {
alert("here");
$http({
method : 'POST',
url : '/create'
})
}
....
}]);
My form is below:
<form class="form-inline" ng-submit="csvurls()">
<input type="text" id="inlineFormInput">
<button type="submit" class="btn btn-primary">Submit</button>
</form>
When I click submit I can see the alert however, I don't think the call to /create is being initiated. I don't see any errors in the log either.
FWIW I am also using ng-file-upload in my application.
You need to add $http as a dependency like this:
app.controller('MyCtrl', ['$scope', 'Upload', '$http', '$timeout', function ($scope, Upload, $http, $timeout) {
I have school task.
We have a HTML code like this:
<html ng-app="myTest">
<head><script type="text/javascript" src="../myScript.js"></script>
</head>
<body id="tst" class="textpage" ng-controller="TestController as testcon">
<form class="" id="frm" ng-submit="doStuff()">
<div class="form-group">
{{testinfo}}
</div>
<div class="form-group">
<button type="submit" id="sbtn" name="sbtn">testSubmit</button>
</div>
</form>
</body>
</html>
Content of javascript with name myScript.js is this:
var tester = angular.module('myTest', ['ui.mask']);
tester.controller('TestController', ['$scope', '$http', '$location', '$window', function ($scope, $http, $location, $window) {
$scope.doStuff = function () {
{
$scope.testinfo = 'unknown value';
};
};
}
]);
I have option to add new javascript.
But I am not possible to get value from $scope.testninfo.
I cannot edit existing JavaScript and cannot edit HTML file. I can just add new javascript.
Is there option how to get value from $scope.testinfo in another javascript?
Thanks.
You can use broadcast
From controller 1 we broadcast an event
$scope.$broadcast('myEvent',anyData);
controller 2 will receive our event
$scope.$on('myEvent', function(event,anyData) {
//code for controller 2
});
here anyData represent your object to be passed
Use ng-model.
<div class="form-group">
<input type="text" ng-model="testinfo">
</div>
I dont think it is possible without appending the existing javascript/html. Because the $scope of the TestController cannot be accessed from another controller (file).
If you COULD append the HTML you could use the $rootscope, in that way the value, which is set by the TestController is accessible from another controller. Or you can add a Global app value. I created a fiddle which show the two options: https://jsfiddle.net/Appiez/wnyb9pxc/2/
var tester = angular.module('myTest', []);
tester.value('globalVar', { value: '' });
tester.controller('TestController', ['$rootScope', '$scope', '$http', '$location', '$window', 'globalVar', function ($rootScope, $scope, $http, $location, $window, globalVar) {
$scope.doStuff = function () {
{
$rootScope.testinfo = 'this is the new value';
globalVar.value = 'a global value';
};
};
}
]);
tester.controller('TestController2', ['$rootScope', '$scope', 'globalVar', function ($rootScope, $scope, globalVar) {
$scope.doStuff2 = function () {
{
alert($rootScope.testinfo);
alert(globalVar.value);
};
};
}
]);
This is what services are for in angular. They ferry data across controllers. You can use NG's $broadcast to publish events that contain data, but Providers, Services, and Factories are built to solve this.
angular.module('krs', [])
.controller('OneCtrl', function($scope, data){
$scope.theData = data.getData();
})
.controller('TwoCtrl', function($scope, data){
$scope.theData = data.getData();
})
.service('data', function(){
return {
getData: function(){
return ["Foo", "Bar"];
}
}
});
Here's a fiddle to help get you into the swing of things. Good luck in school!
I was given the following code to use to get the data I need, but it is not working for me. What am I doing wrong here. I have tried many things from the Angular.js docs and other stack overflow posts, but nothing has worked for me.
someurl
header: Content-Type = application/json
Pass in the following json:
{
"userID": "SomeUSER",
"password": "SomePSWD"
}
Below is the code I am using and it is not working.
function getGroup($scope, $http) {
$http.get('SOMEURL?callback=JSON_CALLBACK&userID=SomeUSER&password=SomePSWD ').
success(function(data) {
$scope.group = data;
});
}
this angularjs demo app show how to use http.jsonp
var httpJsonDemoController = angular.module('HttpJsonDemo', []);
httpJsonDemoController.controller('DataController', ['$scope', '$http', function($scope, $http) {
$http.jsonp("http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Waseem%20Hero").
success(function(data) {
$scope.data = data;
$scope.name = data.name;
$scope.salutation = data.salutation;
$scope.greeting = data.greeting;
}).
error(function (data) {
$scope.data = "Request failed";
});
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.11/angular.min.js"></script>
<div id="wrapper" ng-app="HttpJsonDemo">
<div ng-controller="DataController">
<pre ng-model="data">
{{data}}
</pre>
<input ng-model='name' />
{{name}}
<input ng-model='salutation' />
{{salutation}}
<input ng-model='greeting' />
{{greeting}}
</div>
</div>
So after learning a bit of AngularJS I was able to get a controller to call an API and store the results in a variable, which is then displayed on my page (whew...). If I go to:
http://127.0.0.1:3000/#/search
I see the page with the submit form but without the results, and if I go to:
http://127.0.0.1:3000/#/search?query=deep&learning
I see the page with the submit form + the results for the "deep & learning" query. The problem is: I have to enter "?query=deep?learning" manually, I'm unable to use the submit form to get there. I use this code:
<form name='input' action='#search' method='get'>
<div class='input-group'>
<input type='text'
class='form-control'
placeholder='Enter query.'
name='query'>
<div class='input-group-btn'>
<button class='btn btn-default' type='submit'><i class='fa fa-search'></i></button>
</div>
</div>
</form>
With this submit form, if I enter "deep & learning" in the form, I get to
http://127.0.0.1:3000/?query=deep&learning#/search
How do I change my code so entering "deep & learning" would get me to:
http://127.0.0.1:3000/#/search?query=deep&learning
?
Thank you
UPDATE1: code for routes:
var myApp = angular.module('myApp', ['ngRoute'])
.factory('myQuery', ['$http', function($http) {
var doRequest = function(query) {
return $http({
method: 'GET',
url: 'http://127.0.0.1:3000/api/v0/docs?search=' + query
});
};
return {
results: function(query) { return doRequest(query); }
};
}]);
myApp.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl : 'pages/home.html',
controller : 'mainController'
})
.when('/search', {
templateUrl : 'pages/search.html',
controller : 'searchController'
});
});
myApp.controller('mainController', function($scope) {
// ...
});
myApp.controller('searchController', ['$scope', '$routeParams', 'myQuery', function($scope, $routeParams, myQuery) {
myQuery.results($routeParams.query)
.success(function(data, status, headers) {
$scope.count = data.count;
$scope.results = data.results;
});
}]);
It should simply a matter of changing the action attribute value to get the URL format you want.
In other words:
<form name='input' action='search' method='get'>
Note that the destination URI is no longer prefixed with a hash.
When it is prefixed with a hash as you have it at the moment, it's actually equivalent to directing the submission to the root (i.e. '/') using search as the page anchor.
From this stackoverflow question, my understanding is that I should be using services to pass data between controllers.
However, as seen in my example JSFiddle, I am having trouble listening to changes to my service when it is modified across controllers.
angular.module('myApp', [])
.controller('Ctrl1', function ($scope, App) {
$scope.status = App.data.status;
$scope.$watch('App.data.status', function() {
$scope.status = App.data.status;
});
})
.controller('Ctrl2', function ($scope, App) {
$scope.status = App.data.status;
$scope.$watch('status', function() {
App.data.status = $scope.status;
});
})
.service('App', function () {
this.data = {};
this.data.status = 'Good';
});
In my example, I am trying to subscribe to App.data.status in Ctrl1, and I am trying to publish data from Ctrl1 to App. However, if you try to change the input box in the div associated with Ctrl2, the text does not change across the controller boundary across to Ctrl1.
http://jsfiddle.net/VP4d5/2/
Here's an updated fiddle. Basically if you're going to share the same data object between two controllers from a service you just need to use an object of some sort aside from a string or javascript primitive. In this case I'm just using a regular Object {} to share the data between the two controllers.
The JS
angular.module('myApp', [])
.controller('Ctrl1', function ($scope, App) {
$scope.localData1 = App.data;
})
.controller('Ctrl2', function ($scope, App) {
$scope.localData2 = App.data;
})
.service('App', function () {
this.data = {status:'Good'};
});
The HTML
<div ng-controller="Ctrl1">
<div> Ctrl1 Status is: {{status}}
</div>
<div>
<input type="text" ng-model="localData1.status" />
</div>
<div ng-controller="Ctrl2">Ctrl2 Status is: {{status}}
<div>
<input type="text" ng-model="localData2.status" />
</div>
</div>
Nothing wrong with using a service here but if the only purpose is to have a shared object across the app then I think using .value makes a bit more sense. If this service will have functions for interacting with endpoints and the data be sure to use angular.copy to update the object properties instead of using = which will replace the service's local reference but won't be reflected in the controllers.
http://jsfiddle.net/VP4d5/3/
The modified JS using .value
angular.module('myApp', [])
.controller('Ctrl1', function ($scope, sharedObject) {
$scope.localData1 = sharedObject;
})
.controller('Ctrl2', function ($scope, sharedObject) {
$scope.localData2 = sharedObject;
})
.value("sharedObject", {status:'Awesome'});
I agree with #shaunhusain, but I think that you would be better off using a factory instead of a service:
angular.module('myApp', [])
.controller('Ctrl1', function ($scope, App) {
$scope.localData1 = App.data;
})
.controller('Ctrl2', function ($scope, App) {
$scope.localData2 = App.data;
})
.factory('App', function () {
var sharedObj = {
data : {
status: 'Good'
}
};
return sharedObj;
});
Here are some information that might help you understand the differences between a factory and a service: When creating service method what's the difference between module.service and module.factory