ng-click刷新页面而不是提交 [英] ng-click refreshes the page instead of submit

查看:70
本文介绍了ng-click刷新页面而不是提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有角度的Web表单,该表单从用户输入并插入数据库.我正在使用jersey-jackson rest Web服务并休眠.但是当我尝试提交表单时,上一页具有超链接刷新到当前页面,然后重新加载当前页面(在网络日志中可以看到上一页的加载).http请求中指定的url甚至没有被调用.以下是我的代码

Hi i have an angular web form which takes input from the user and inserts into the database.I am using jersey-jackson rest web services and hibernate.But when i try to submit the form,the previous page which had the hyperlink to the current page is refreshed and the current page is reloaded again(Loading of previous page is seen in the network log).The url specified in the http request is not even invoked.Following is my code

<div id="main">
  <h1>Create Leave</h1>
    <form class="form-horizontal" ng-controller="MyAddController" >
        <div class="form-group">
            <label for="employeeName" class="col-sm-3 control-label">Employee Name</label>
            <div class="col-sm-6">
                <input type="text" id="num" class="form-control" ng-model="num" />
            </div>
            <div class="col-sm-3"></div>

        </div>
        
           <div class="form-group">
            <label for="leaveType" class="col-sm-3 control-label">Leave Type</label>
            <div class="col-sm-2">
                <select id="leaveType" class="form-control" ng-model="leaveType">
                    <option value="">Hospital</option>
                    <option value="female">leave type 2</option>
                     <option value="female">leave type 3</option>
                      <option value="female">leave type 4</option>
                       <option value="female">leave type 5</option>
                        <option value="female">leave type 6</option>
                </select>
            </div>
            <div class="col-sm-7"></div>
        </div>
       
        <div class="form-group">
            <label for="leaveStartDate" class="col-sm-3 control-label">Leave Start Date</label>
            <div class="col-sm-2">
                <input type="date" id="startDates" class="form-control" ng-model="startDate" />
            </div>
            <div class="col-sm-7"></div>
        </div>
       
         <div class="form-group">
            <label for="leaveEndDate" class="col-sm-3 control-label">Leave End Date</label>
            <div class="col-sm-2">
                <input type="date" id="endDate" class="form-control" ng-model="endDate" />
            </div>
            <div class="col-sm-7"></div>
        </div>
        
     
        
        <div class="form-group">
            <div class="col-sm-3"></div>
            <div class="col-sm-2">
                <span><b>Is Half Day leave</b></span>
                <div class="radio">
                    <label><input value="Yes" type="radio" name="halfDay" ng-model="isHalfDay" />Yes</label>
                </div>
                <div class="radio">
                    <label><input value="No" type="radio" name="halfDay" ng-model="isHalfDay" />No</label>
                </div>
            </div>
          
        </div>

        <input type="submit" value="Save" ng-click='add();' class="btn btn-primary col-sm-offset-3" /> 
        <input type="reset" value="Reset" ng-click="resetForm()" class="btn" /> <br/>
		
   </form>
   
  <script>
	function MyAddController($scope, $http) {
		$scope.add = function() {
			$http.get("webapi/blog/create", {
				params : {
					
					signum : $scope.num,
					leaveType : $scope.leaveType,
					startDate : $scope.startDate,
					endDate : $scope.endDate,
					isHalfDay : $scope.isHalfDay
				}
			}).success(function(data, status, headers, config) {
				if (data) {
					$scope.data = data;
					alert("success")
				}
			}).error(function(data, status, headers, config) {
				alert("error");
			})
		}

	}
</script>

和bean类

package com.king.entity;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class LeaveDetails {
	
	@Id
	private String num;
	public String getnum() {
		return num;
	}
	public void setnum(String num) {
		this.num = num;
	}
	public String getLeaveType() {
		return leaveType;
	}
	public void setLeaveType(String leaveType) {
		this.leaveType = leaveType;
	}
	public Date getStartdate() {
		return startdate;
	}
	public void setStartdate(Date startdate) {
		this.startdate = startdate;
	}
	public Date getEndDate() {
		return endDate;
	}
	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}
	public String getIsHalfDay() {
		return isHalfDay;
	}
	public void setIsHalfDay(String isHalfDay) {
		this.isHalfDay = isHalfDay;
	}
	private String leaveType;
	private Date startdate;
	private Date endDate;
	private String isHalfDay;
	
	
	

}

DAO

package com.king.dao;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.king.entity.Blog;
import com.king.entity.LeaveDetails;
import com.king.test.HibernateTest;

public class AddLeaveDao {
	
	public void addDetails(LeaveDetails data) {
		Session session = HibernateTest.getSession();
		Transaction ts = session.beginTransaction();
		session.saveOrUpdate(data);
		session.flush();
		ts.commit();
		session.close();
	}

和WS

package com.king.webapi;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.ws.rs.BeanParam;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;

import com.king.dao.AddLeaveDao;
import com.king.dao.BlogDao;
import com.king.dao.LeaveDao;
import com.king.entity.Blog;
import com.king.entity.LeaveBalance;
//import com.king.entity.Love;
import com.king.entity.LeaveDetails;

@Path("/blog")
public class BlogWS {

	@GET
	@Path("list")
	@Produces({ "application/json" })
	public List<LeaveBalance> list() {
		List l= new LeaveDao().getAllLeaves();
		Iterator i=l.iterator();
		while(i.hasNext())
		{
			LeaveBalance m=(LeaveBalance)i.next();
			System.out.println(m.getLeaveBalance());
		}
		
		return l;
	}

	@GET
	@Path("create")
	@Produces({ "application/json" })
	public String create(@BeanParam LeaveDetails ld) {
		System.out.println("Entered here");
		new AddLeaveDao().addDetails(ld);
		System.out.println("Returned  here");
		return "{}";
	}

	@GET
	@Path("findById")
	@Produces({ "application/json" })
	public Blog findById(@QueryParam("id") String id) {
		return new BlogDao().findBlogById(id);
	}

	@GET
	@Path("update")
	@Produces({ "application/json" })
	public String update(@BeanParam Blog blog) {
		new BlogDao().updateBlog(blog);
		return "{}";
	}
}

edit:我正在使用的实际js

edit:actual js i am using

var app = angular.module('myApp', ['ui.calendar','ui.router']);
app.controller('myNgController', ['$scope', '$http', 'uiCalendarConfig', function ($scope, $http, uiCalendarConfig) {
    
    $scope.SelectedEvent = null;
    var isFirstTime = true;
 
    $scope.events = [];
    $scope.eventSources = [$scope.events];
    $scope.events.push({
        title: "Leave",
        description: "jahsojoaisjjoijaso",
        start: new Date("2017-05-03"),
        end: new Date("2017-05-03"),
        allDay : false,
        stick: false
    });
 
 
    /*//Load events from server
    $http.get('/home/getevents', {
        cache: true,
        params: {}
    }).then(function (data) {
        $scope.events.slice(0, $scope.events.length);
        angular.forEach(data.data, function (value) {
         
        });
    });*/
 
    //configure calendar
    $scope.uiConfig = {
        calendar: {
            height: 450,
            editable: false,
            displayEventTime: false,
            header: {
                left: 'month basicWeek basicDay agendaWeek agendaDay',
                center: 'title',
                right:'today prev,next'
            },
            eventClick: function (event) {
                $scope.SelectedEvent = event;
            },
            eventAfterAllRender: function () {
                if ($scope.events.length > 0 && isFirstTime) {
                    //Focus first event
                    uiCalendarConfig.calendars.myCalendar.fullCalendar('gotoDate', $scope.events[0].start);
                    isFirstTime = false;
                }
            }
        }
    };
 
}]);

app.controller("MyDbController",function ($scope, $http) {
	//$scope.data = [{title: 'welcome hello'},{title: 'great testing'}];

	$http.get("webapi/blog/list", {}).success(function(data, status, headers, config) {
		$scope.data = data;
	}).error(function(data, status, headers, config) {
		alert("error");
	})
});
app.controller("MyAddController",function ($scope, $http) {
	$scope.add = function() {
	$http.get("webapi/blog/create", {
		params : {
			signum : $scope.num,
			leaveType : $scope.leaveType,
			startDate : $scope.startDate,
			endDate : $scope.endDate,
			isHalfDay : $scope.isHalfDay
			
		}
	}).success(function(data, status, headers, config) {
		if (data) {
			$scope.data = data;
			alert("success");
		}
	}).error(function(data, status, headers, config) {
		alert("error");
	})
	}
});

app.config(function($stateProvider){
	$stateProvider
	.state("applyLeave",{
		url:"/applyLeave",
		templateUrl:"html/LeaveApply.html",
		controller:"leaveController",
		controllerAs:"leaveController"
	});
	v.controller("leaveController",function($scope)
			{
		
			})
});

当我单击保存时,这是浏览器中显示的网址格式. http://localhost:8081/hibernate-jersey-angularjs/?halfDay = No#/applyLeave .我不明白为什么

When i click on save this is the url pattern shown in the browser. http://localhost:8081/hibernate-jersey-angularjs/?halfDay=No#/applyLeave .I dont understand why

请帮助

推荐答案

最简单的解决方法是从调用add()方法的按钮中删除type="submit",将其替换为type="button"

Easiest way to fix this is to remove type="submit" from your button that calls the add() method, replacing it with type="button"

 <input type="button" value="Save" ng-click='add()' class="btn btn-primary col-sm-offset-3" /> 

否则,您需要在表单上添加ng-submit="add()",然后使用type = submit从按钮中删除ng-click="add()".

Otherwise, you need to add ng-submit="add()" on your form, and then remove the ng-click="add()" from your button with type=submit.

您的表单应如下所示:

 <form class="form-horizontal" ng-controller="MyAddController" ng-submit="add()">

您的按钮是这样的:

<input type="submit" value="Save" class="btn btn-primary col-sm-offset-3" /> 

这两种方法都应该起作用.

Either of these should work.

顺便说一句,您不需要使用;在ng-click指令的末尾.另外,请尝试使用按钮标记代替保存按钮的输入.

By the way, you don't need to use ; at the end of an ng-click instruction. Also, try using the button tag instead of input for the save button.

您忘记了声明要在html中使用的应用程序.在HTML代码的正文上,使用ng-app='myApp'

You forgot to declare the app to use in your html. On the body of your HTML code, use ng-app='myApp'

这篇关于ng-click刷新页面而不是提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆