How to add submit function to my ng-controller - javascript

I am trying to learn angular so forgive my stupid mistakes and ignorance. That being said,
I add data to my scope when I create my controller ProducerCtrl. This works before I add anything else. When I add the addname function it breaks my data fetch. I am sure I am doing something wrong because I don't know what I am doing. I would like to have these
two bits of code work. Maybe I need to move one or both to another area.
<html><head>
<title></title>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script>
<script>
var eventApp = angular.module('eventApp', []);
var szAction = "/GoGetData";
var szAction2 = "/GoPostData" })";
eventApp.controller('ProducerCtrl', ['$scope', '$http', function (scope, http) {
http.get(szAction).success(function (data) {
scope.producer = data;
});
$scope.addName = function () {
http.post(szAction2, scope.producer);
};
}]);
</script>
</head>
<body>
<div ng-app="eventApp">
<div ng-controller="ProducerCtrl">
Name:<input ng-model="producer.Name" type="text" /><br>
Hello {{producer.Name}}
<form ng-submit="addName()">
<input ng-model="producer.Name" type="text">
<input type="submit" value="add">
</form>
</div>
</div>
</body></html>

I've made some changes on your code. When you click on add will prompt an alert.
Your HTML:
<body>
<div ng-app="eventApp">
<div ng-controller="ProducerCtrl">
Name:<input ng-model="producer.Name" type="text" /><br />
Hello {{producer.Name}}
<form ng-submit="addName()">
<input ng-model="producer.Name" type="text" />
<input type="submit" value="add" />
</form>
</div>
</div>
<body>
Your Angular code:
var eventApp = angular.module('eventApp', []);
eventApp.controller('ProducerCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.producer = { Name : '' };
$scope.addName = function () {
alert($scope.producer.Name);
};
}]);
See here.
Take a look here to check $http.

Related

Angular unable to load view after url change

I am trying to learn angularjs.I wan't to share data between two controllers of two different pages. After googling came to know about services and created one service. From one page I am able to call my rest service and able to get data. After I am trying to redirect to different page. URL is changing but page is not loaded. Stuck here. Please find the code below. Anybody can help me where I am doing wrong?
data.html
<!DOCTYPE html>
<html>
<head>
<base href="/">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-route.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-resource.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.16/angular-resource.min.js"></script>
<script src="app.js"></script>
<script src="usercontroller.js"></script>
<script src="userservice.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="UserController" >
<form>
<input type="text" name="Name" ng-model="user.userName"> Name <br/>
<input type="text" name="password" ng-model="user.password"> Password <br/>
<button type="submit" ng-click="getUser(user)" >Submit</button>
</form>
data2.html
<!DOCTYPE html>
<html>
<head>
<base href="/">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-route.js"></script>
<script src="app.js"></script>
<script src="usercontroller.js"></script>
<script src="userservice.js"></script>
</head>
<body>
<div ng-controller="UserController2" >
<form>
<input type="text" name="Name" ng-model="user.userName"> Name <br/>
<input type="text" name="password" ng-model="user.password"> Password <br/>
<button type="submit" ng-click="shareUser()" >Submit</button>
</form>
</div>
app.js
var App = angular.module('myApp',['ngRoute','ngResource']);
App.config(['$routeProvider',
function (
$routeProvider
) {
$routeProvider.
when('/home', {
templateUrl: 'data.html',
controller: 'UserController'
}).
when('/welcome', {
templateUrl: '/data2.html',
controller: 'UserController2'
}).
otherwise({
redirectTo: '/home'
});
}]);
usercontroller.js
App.controller('UserController', ['$scope', 'UserService', '$window', function($scope, UserService,$window,$location) {
alert("inside user controller");
var self = this;
$scope.user={};
$scope.user.userName="murali";
$scope.user.password="murali123";
$scope.getUser = function(user){
alert("inside function");
UserService.getUser(user).then(function(data){
alert("data::"+JSON.stringify(data.userName));
$window.location.href ='/welcome';
});
};
}]);
App.controller('UserController2', ['$scope', 'UserService', function($scope, UserService) {
alert("inside user controller");
$scope.user={};
$scope.findUser = function(){
alert("inside function");
$scope.user = UserService.findUser();
alert("userName::"+$scope.user.userName);
};
}]);
userservice.js
App.factory('UserService', ['$http', '$q', function($http, $q){
var user = {};
return {
getUser : function(user){
return $http.post('http://localhost:8080/user/login', angular.toJson(user))
.then(
function(response){
alert(JSON.stringify(response.data));
user=response.data;
return response.data;
},
function(errResponse){
console.error('Error while getting response');
return $q.reject(errResponse);
}
);
},
shareUser : function(){
return user;
}
};
}]);
If you redirect the entire page is reloaded and the service is created from 0, no data is saved, unless you store it in cookie or local/session storage. But I see you are using angular-route, so, you can still get it done.
First, when using angular-route, the views does not need to be a full html doc and instead just a piece of it. Example:
index.html
<!DOCTYPE html>
<html>
<head>
<base href="/">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"> </script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-route.js"></script>
<script src="app.js"></script>
<script src="usercontroller.js"></script>
<script src="userservice.js"></script>
</head>
<body>
<div ng-app="myApp">
<ng-view></ng-view> <!-- Required by angular-route -->
</div>
</body>
</html>
Please, note the <ng-view></ng-view> element, it is required by angular-route and is where the views will be loaded.
data.html
<form>
<input type="text" name="Name" ng-model="user.userName"> Name <br/>
<input type="text" name="password" ng-model="user.password"> Password <br/>
<button type="submit" ng-click="getUser(user)" >Submit</button>
</form>
data2.html
<form>
<input type="text" name="Name" ng-model="user.userName"> Name <br/>
<input type="text" name="password" ng-model="user.password"> Password <br/>
<button type="submit" ng-click="findUser()" >Submit</button>
</form>
Note that in data2.html I changed ng-click="shareUser()" to ng-click="findUser()" as UserController2 does not have a shareUser function.
Now, in UserController instead of using window.location.href ='/welcome'; use $location.path('/welcome');, this is what you need to use to navigate without reloading the entire page, angular-route will do the magic. You will need to add the $location service as a dependency.
In UserController2, change UserService.findUser(); to UserService.shareUser(); because UserService does not have a findUser function, and I think shareUser is what you are trying to use.
Also, take a look again to the $routeProvider configuration, '/data2.html' might be pointing to the wrong location.
And you are ready, reload the page and happy coding.

Why isn't the submit button working?

I have written this code testing out the $scope feature as I have just started learning AngularJS. However, whenever I click the submit button, nothing happens.
This is my JS file below.
var app = angular.module('permissions', []);
app.controller('testAppCtrl', ['$scope', function testAppCtrl($scope) {
'use strict';
$scope.details = {
itemId: "",
userID: ""
};
$scope.register = function () {
console.log('User clicked change', details.itemId);
};
$scope.fullDetails = function () {
return details.itemId + " " + details.userId;
};
}]);
This is my PHP file below.
<script type="text/javascript" src="include/js/angular-permission-test.js"></script>
<div id="myForm">
<form name="myForm" action="" ng-app="permissions" ng-submit="register()">
<h1>Test</h1>
<body ng-controller="testAppCtrl">
ItemId: <input type="text" ng-model="details.itemId"> {{details.itemId}}<br><br>
UserId: <input type="text" ng-model="details.userId"> {{details.userId}}<br><br>
<input name="submitBtn" type="submit" value="Change" ng-click="register()">
{{ fullDetails() }}
</body>
</form>
</div>
I can't seem to find the problem in the code. I have tried many solutions but none have had any apparent effect on it.
Also, any improvements to the code will be appreciated.
Thanks in advance.
The problem I think is with the structure of your HTML. Because angular scope is resolved from the HTML elements parent child hierarchy.
Your testAppCtrl is in body (which is inside your form), the register() function is inside the scope of testAppCtrl (but you are trying to access it outside the body). So, you cannot access it from outside in hierarchy. Keep the Body outside and form inside. Also the ng-app should be at the same or higher level of your ng-controller. Because you can bind your controllers to the app/module and not the reverse.
So, the code should be something like this,
<body ng-app="permissions" ng-controller="testAppCtrl">
<div id="myForm">
<form name="myForm" action="" ng-submit="register()">
<h1>Test</h1>
ItemId: <input type="text" ng-model="details.itemId"> {{details.itemId}}<br><br>
UserId: <input type="text" ng-model="details.userId"> {{details.userId}}<br><br>
<input name="submitBtn" type="submit" value="Change" ng-click="register()">
{{ fullDetails() }}
</form>
</div>
</body>
Couple of things I noticed. ng-app should be declared inside ng-controller.
you are returning plain variables instead of the scope variables.
Anyway, here's the fix.
var app = angular.module('permissions', []);
app.controller('testAppCtrl', ['$scope',
function testAppCtrl($scope) {
'use strict';
$scope.details = {
itemId: "",
userID: ""
};
$scope.register = function() {
console.log('User clicked change', $scope.details.itemId);
};
$scope.fullDetails = function() {
return $scope.details.itemId + " " + $scope.details.userId;
};
}
]);
<!DOCTYPE html>
<html ng-app="permissions">
<head>
<script data-require="angular.js#1.3.13" data-semver="1.3.13" src="https://code.angularjs.org/1.3.13/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="testAppCtrl">
<div id="myForm">
<form name="myForm" ng-submit="register()">
<h1>Test</h1> ItemId:
<input type="text" ng-model="details.itemId" />{{details.itemId}}
<br />
<br />UserId:
<input type="text" ng-model="details.userId" />{{details.userId}}
<br />
<br />
<input name="submitBtn" type="submit" />{{ fullDetails() }}
</form>
</div>
</body>
</html>

ng-bind-html Unable to parse correct HTML and bind it

My controller is the following:
myApp.controller('actionEditController', ['$scope', '$stateParams', '$sce',function ($scope, $stateParams, $sce) {
$scope.table="<p>OOPSY</p>";
$scope.test="<p>TEST</p>";
$.get(apiHost + "/action/entity/" + $stateParams.id)
.success(function (response) {
var action = response['RESPONSE'];
action.params = JSON.parse(action.paramsJson);
$scope.$apply(function () {
$scope.table = $.hbs("/templates/action.hbs", action);
});
console.log(" table is "+$scope.table);
})
.error(function (jqXHR, textStatus, errorThrown) {
console.error("Error retrieving action");
});
}]);
The output of console.log(table) is:
<div>
<input name="name" type="text" value="EXPIRY_SM00004_BROWSED"/>
<input name="id" type="text" readonly="readonly" value="AC0000E1"/>
<input name="type" type="text" readonly="readonly" value="SCHEDULE"/>
<input name="priority" type="text" value="LOW"/>
<input name="eventName" type="text" value="expiry.SM00004.browsed"/>
<input name="space" type="text" value="hybrid"/>
<input name="at" type="number" value=59400000/>
<input name="on" type="number" value=172800000/>
</div>
<script src="lib/angular/angular-sanitize.min.js"></script>
My html file:
<div ng-app="broConsoleApp" ng-controller="actionEditController" >
<h2 class="marcellus text-center"> EDIT ACTION </h2>
<div ng-bind-html="table">
</div>
<div ng-bind-html="test"></div>
</div>
The test is getting printed however table is not getting printed. I think it is because of some new line characters in the output? I tried replacing them with :
$scope.table.replace(/\n/g,''))
However I am still not getting an output for table. Someone please help me in formatting this rendered output just right so that ng-bind can bind it.
I don't think there is any thing wrong with the html with regards to special characters etc. I am begining to think ngBindHtml cannot handle this at all.
PLease check the plunker: http://plnkr.co/edit/PcAUERYziJtw0k1f1XjT?p=preview
I took the plunker from angular JS and modified it to add just one of the input buttons in your html and it does not render.
$scope.myHTML =
'I am an <code>HTML</code>string with ' +
'links! and other <em>stuff</em>' +
'<input name="name" type="text" value="EXPIRY_SM00004_BROWSED"/>';
it seems to be working with $sce.trustAsHtml :
view:
<div ng-app="app" ng-controller="Ctrl">
<div ng-bind-html="table"></div>
<div ng-bind-html="test"></div>
</div>
js:
angular.module('app', [])
.controller('Ctrl', function($scope, $sce) {
$scope.table = $sce.trustAsHtml('<p>this is a test</p>');
$scope.test = $sce.trustAsHtml('<h3>TEST</h3>');
});
working example: https://jsfiddle.net/r646z10y/1/

form is undefined in controller

I have a form...
<form name="userForm" ng-submit="setUsers()">
<input type="number" class="form-control" name="users" ng-model="users.num" required>
<button type="submit" class="btn btn-primary" ng-disabled="userForm.$invalid">Continue</button>
</form>
And in my controller I want to see if the form is $pristine...
angular.module('myApp')
.controller('myController', ['$http', '$scope', function($http, $scope) {
$scope.userForm = {};
$scope.users = {};
console.log($scope.userForm) //empty object
console.log($scope.userForm.$pristine); // undefined
console.log($scope.users); //empty object
console.log($scope.users.num); //undefined
}]);
What am I doing incorrectly that I cannot get the form in my controller? I am using AngularJs 1.3
Thanks!
You cannot access form because you are trying to do that before it exist. Please see code example below that can helps you.
var app = angular.module('app',[]);
app.controller('fCtrl', function($scope){
$scope.setForm = function (form) {
$scope.userForm = form;
$scope.users = {};
console.log($scope.userForm) //empty object
console.log($scope.userForm.$pristine); // undefined
console.log($scope.users); //empty object
console.log($scope.users.num); //undefined
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="fCtrl">
<form name="userForm" ng-submit="setUsers()">
<input type="number" class="form-control" name="users" ng-model="users.num" required>
<button type="submit" class="btn btn-primary" ng-disabled="userForm.$invalid">Continue</button>
<span ng-init="setForm(userForm);"></span>
</form>
</div>
</div>
You have to wait for the form to be available. If you access it after the controller has been loaded you will be able to gain access to it.
Test it quickly with something like:
console.log($scope.userForm); // undefined
$scope.logForm= function(){
console.log($scope.userForm); // defined
};
Open your console and see this bin http://jsbin.com/loqic/1/edit?js,output

anchor ng-click calling 2 methods

We are using angular to do like/unlike behavior for our app.
Code for html
<html>
<body ng-app="myApp">
<div ng-controller="newsCntrl" >
<form ng-submit="post()" name="postForm" id="postForm" >
<input type="submit" id="submit" value="Submit"/>
</form>
Like</span>
</div>
</body>
</html>
Code for controller
myApp.controller("newsFeedCtrl", function ($scope, $http) {
console.log("inside newsFeedCtrl");
$scope.post() = function() {
console.log("posting");
}
$scope.likePost = function(postId) {
console.log("liking post");
}
});
The problem is when we click on like; it also calls post function which should not be happening.
Are we missing anything here?
There is a mismatch between the controller name in the HTML:
<div ng-controller="newsCntrl" >
and the controller in the JS:
myApp.controller("newsFeedCtrl", function ($scope, $http)
If I fix it, it seems to work.
Check this fiddle
You should remove syntax error
Code for html:
<html>
<body ng-app="myApp">
<div ng-controller="newsCntrl">
<form ng-submit="submitPost()" name="postForm" id="postForm">
<input type="submit" id="submit" value="Submit"/>
</form>
Like
</div>
</body>
</html>
Code for controller:
myApp.controller("newsFeedCtrl", function ($scope, $http) {
console.log("inside newsFeedCtrl");
$scope.submitPost = function() {
console.log("posting");
}
$scope.likePost = function(postId) {
console.log("liking post");
}
});

Categories