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");
}
});
Related
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.
I have simple form. I need to show errors about my fields.
<html lang="en" ng-app="MyApp">
<head></head>
<body ng-controller="AppCtrl">
<form name="myForm" id="myForm">
<input type="text" ng-model="field" name="myField" />
<div ng-show="myForm.myField.$error" style="color: red">
{{myForm.myField.$error}}
</div>
</form>
<script src="bower_components/angular/angular.js"></script>
<script src="controller.js"></script>
</body>
</html>
And this is my controller
angular.module('MyApp',[])
.controller('AppCtrl', function() {
var form = document.getElementById("myForm");
var error = {
myField: 'Error in this field'
};
for (var key in error) {
form[key].$error = error[key];
}
});
Why I can't see error about myField? I get only '{}'
You're not binding the form to AngularJS correctly
<form name="myForm" id="myForm">
This says your form is called myForm, so in your controller you should be using $scope.myForm
No need for var form = document.getElementById("myForm");, just use $scope.myForm in your controller
Try this to see if you access the the form from AngularJS
angular.module('MyApp',[])
.controller('AppCtrl', function($scope) {
$scope.myForm.myField.$error = "just to see it work";
});
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>
I have an HTML page that looks like this:
<div ng-controller="MyController">
<form action="/my-url" method="POST">
...
</form>
</div>
This page is an ANgularJS app. Inside of it, I then have the following:
<script type="text/javascript">
myApp.controller('MyController', ['$scope', function($scope) {
$scope.submitForm = function() {
// how?
}
}]);
</script>
How do I submit the form from the submitForm function? In other words, I am trying to programmatically submit the form. How do I do that?
Thank you!
use this:
<div ng-controller="MyController">
<form ng-submit="submitForm()">
...
<button type="submit">submit here</button>
</form>
</div>
see in detail
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.