Submit a form with POST action using angular - javascript

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) {

Related

Dynamic loading Angular Controller

I am trying to load controllers dynamically using ocLazyLoad :
$ocLazyLoad.load('./ctrls/login.js');
But am getting this error saying:
The controller with the name 'loginCtrl' is not registered.
angular.module('optimusApp')
.controller('loginCtrl', function ($scope, $rootScope, $location, $http) {});
app.js
angular.module("optimusApp", ['ngRoute', 'oc.lazyLoad']);
angular.module('optimusApp')
.controller('globalCtrl', function ($rootScope, $location, $http, $routeParams, $ocLazyLoad) {
$ocLazyLoad.load('./ctrls/login.js');
});
I made it work by using ng-if
app.js
var optimusApp = angular.module("optimusApp", ["ngRoute", "oc.lazyLoad"])
.controller("globalCtrl", function ($rootScope, $location, $http, $routeParams, $ocLazyLoad) {
$ocLazyLoad.load("./js/app/login.js").then(function() {
console.log("loginCtrl loaded");
$rootScope.loginActive = true;
}, function(e) {
console.log("error");
});
});
login.js
optimusApp.controller('loginCtrl', function ($scope, $rootScope, $location, $http) {
});
HTML
<div ng-if="loginActive" ng-controller="loginCtrl">
</div>
Basically you will get the "registration error" if your ng-controller is in the page before you have the JS loaded.
So the ng-if is a solution, or I see you have ngRoute. So you could set ocLazyLoad to load the controller when entering a specific state.

have my angular controller check to see what ui-view it's located in with ui-router

I'm using ui-router with angularjs. I want to write a template for a view that will show a image depending on what the view is. here's my example state.
$stateProvider
.state('index', {
url: "",
views: {
"topStormtrooper": {
templateUrl: '/components/stormtroopers/stormtroopers.html',
controller: "stormtroopersCtrl"
},
"bottomStormtrooper": {
templateUrl: '/components/stormtroopers/stormtroopers.html',
controller: "stormtroopersCtrl"
}
}
})
my controller looks like this
.controller('stormtroopersCtrl', ['$scope', '$http', '$stateParams', function ($scope, $http, $stateParams) {
//
$scope.stormtrooper = $stateView; //it should be something like this hopefully
}]);
The template is all the same just the image will be different depending which view it is loaded into. Currently I just added a new controller for each view and load the image based on that. But I feel like I should be able to do this with just one controller and the controller should be able to detect what the view is. I know you can detect the state but I want go deeper and get the view.
Any Ideas?
You can access the current state configuratin object like this:
$state.current
For further information take a look at the $state
You can listen to the $viewContentLoaded function in your controller as per the ui-router documentation
For example:
.controller('stormtroopersCtrl', ['$scope', '$http', '$stateParams', function ($scope, $http, $stateParams) {
$scope.$on("$viewContentLoaded",function(event,viewName){ //listen for when the content is loaded into the view
$scope.currentView = viewName; //assign the view name in a model
console.log($scope.currentView);
//do something because you got the view name now....
});
}]);
You do not need to change your state just for an image in template. You can make it with scope variables.
angular.module('app',[])
.controller('stormtrooperCtrl', ['$scope', function ($scope) {
//
$scope.selected = 0;
$scope.images = [
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSz6dBOOsFVAeSilVEIO9dqwrY4R5gCzEMcrRVZguhYhr9PVJsThQ",
"http://www.wallpapereast.com/static/images/Wallpaper-Nature-8B71.jpg",
"http://www.intrawallpaper.com/static/images/1250654-for-laptop-nature.jpg"
];
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="stormtrooperCtrl">
<button ng-click="selected=0">image1</button>
<button ng-click="selected=1">image2</button>
<button ng-click="selected=2">image3</button>
<div>
<img width="100" ng-src="{{images[selected]}}"/>
</div>
</div>
</div>

JavaScript angular controller get value from scope from another controller

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!

Posting with Angular to Mongo

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'});
}

$modal.open is not working

I want to show a progress dialog as a model by using ui.bootstrap, so I included it as a dependency in my application as follows:
var app = angular.module('app', ['ngRoute','ngCookies','home','ui.bootstrap']);
After injecting it my controller is as follows:
angular.module('home', [])
.controller('homeCtrl', ['$scope', '$http', '$filter', '$route', '$routeParams', '$location', '$rootScope', 'showAlertSrvc', '$modal',
function ($scope, $http, $filter, $route, $routeParams, $location, $rootScope, showAlertSrvc, $modal) {
$scope.open = function () {
var modalInstance = $modal.open({
templateUrl: 'App/Register',
controller: 'registerCtrl',
//size: size,
resolve: {
items: function () {
return $scope.items;
}
}
});
//modalInstance.result.then(function (selectedItem) {
// $scope.selected = selectedItem;
//}, function () {
// //$log.info('Modal dismissed at: ' + new Date());
//});
};
}]);
And my HTML is :
<input type="submit" value="Show Model" class=" novalidate form-control" ng-click="open()" style="background-color:skyblue; height: 45px" />
My View is named as Register.cshtml residing in App directory. Also routing is active at this URL. But when I click the button nothing happens, I wonder if templateUrl expects URL in any other format here. Please suggest what am I missing here.
Try to specify the path to the template with extersions
templateUrl: 'App/Register.cshtml',
Other options for .open look fine.

Categories

Resources