angularjs 为什么我的gridOptions(ng-grid)中的“data”参数总是空的?

iovurdzv  于 12个月前  发布在  Angular
关注(0)|答案(1)|浏览(138)

这个命令...即,

$http.get('http://localhost:8084/nggridtest/tasks')
    .success(function (data) 
    {
        alert(JSON.stringify(data));
        $scope.tasks = data;  // <=== not working???
    });

字符串
.似乎成功检索数据-如我的警报所示.即,
x1c 0d1x的数据
但是,命令-$scope.tasks = data;-似乎没有将数据分配给我的“$scope.tasks”变量-导致空网格...即,



我做错了什么?

更新

下面是更多信息。

  • app.js*
/* global angular */
    var taskApp = angular.module('taskApp', ['ngGrid']);

    var taskController = taskApp.controller('taskController', function taskController($scope, $http) 
    {
        $http.get('http://localhost:8084/nggridtest/tasks')
            .success(function (data) 
            {
                alert(JSON.stringify(data));
                $scope.tasks = data;
            });

        $scope.gridOptions = {
            data: 'tasks',
            columnDefs: [
                {field: 'taskId', displayName: 'taskId'},
                {field: 'taskName', displayName: 'taskName'},
                {field: 'taskDescription', displayName: 'taskDescription'},
                {field: 'taskStartTime', displayName: 'taskStartTime'},
                {field: 'taskEndTime', displayName: 'taskEndTime'},
                {field: 'taskArchived', displayName: 'taskArchived'}
            ]
        };
    });

  • app.css*
.gridStyle
    {
        margin: 0;
        width:100em;
        height:50em;
    }

  • index.jsp *
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <!doctype html>
    <html ng-app="taskApp">
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
            <title>Spring MVC, REST, AngularJS testing</title>
            <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/webjars/jquery/2.1.4/jquery.css" media="screen">         
            <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/webjars/ng-grid/2.0.14/ng-grid.css" media="screen"> 
            <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/webjars/bootstrap/3.3.1/css/bootstrap.css" media="screen"> 
            <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/resources/js/app.css" media="screen"/>  
            <script type="text/javascript" src="${pageContext.request.contextPath}/webjars/jquery/2.1.4/jquery.js"></script>
            <script type="text/javascript" src="${pageContext.request.contextPath}/webjars/angularjs/1.4.4/angular.js"></script>    
            <script type="text/javascript" src="${pageContext.request.contextPath}/webjars/ng-grid/2.0.14/ng-grid.js"></script>  
            <script type="text/javascript" src="${pageContext.request.contextPath}/webjars/bootstrap/3.3.1/js/bootstrap.js"></script>        
            <script type="text/javascript" src="${pageContext.request.contextPath}/resources/js/app.js"></script>        
        </head>
        <body>
            <div ng-controller="taskController">
                <div class='panel panel-primary row container-fluid' style="margin: 2em; padding:0;">
                    <div class='panel-heading' style="margin: 0;">
                        <h1 class='panel-title'>Entries</h1>
                    </div>
                    <div class='panel-body' style="padding:0;">  
                        <div class="gridStyle" ng-grid="gridOptions"></div>
                    </div>                          
                </div>                
            </div>
        </body>
    </html>

  • TaskController.java*
package aaa.bbb.ccc.war;

    import java.util.List;
    import org.apache.logging.log4j.LogManager;

    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.servlet.config.annotation.EnableWebMvc;

    @RestController
    @EnableWebMvc
    public class TaskController
    {
        private static final org.apache.logging.log4j.Logger LOG = LogManager.getLogger("TaskController");

        TaskService taskmanagerservice = new TaskService();

        @RequestMapping(value = "/tasks", method = RequestMethod.GET, headers = "Accept=application/json")
        public List<Task> getAllTasks()
        {
            List<Task> tasks = null;

            try
            {
                tasks = taskmanagerservice.getAllTasks();
            }
            catch (Exception e)
            {
                LOG.error("____________________________getAllTasks____________________________Exception encountered - e.getMessage=" + e.getMessage(), e);
            }

            return tasks;
        }
    }

  • TaskService.java*
package aaa.bbb.ccc.war;

    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.ArrayList;
    import java.util.List;
    import org.apache.logging.log4j.LogManager;

    public class TaskService
    {
        private static final org.apache.logging.log4j.Logger LOG = LogManager.getLogger("TaskService");

        private Connection connection;

        public TaskService()
        {
            connection = DBUtility.getConnection();
        }

        public List<Task> getAllTasks()
        {
            List<Task> tasks = null;

            try
            {
                tasks = new ArrayList<Task>();
                Statement statement = connection.createStatement();
                ResultSet rs = statement.executeQuery("select * from task_list where task_archived=false");
                while (rs.next())
                {
                    Task task = new Task();
                    task.setTaskId(rs.getInt("task_id"));
                    task.setTaskName(rs.getString("task_name"));
                    task.setTaskDescription(rs.getString("task_description"));
                    task.setTaskPriority(rs.getString("task_priority"));
                    task.setTaskStatus(rs.getString("task_status"));
                    tasks.add(task);
                }
            }
            catch (SQLException e)
            {
                LOG.error("____________________________getAllTasks____________________________Exception encountered - e.getMessage=" + e.getMessage(), e);
            }

            return tasks;
        }
    }

  • DBUTILITY *
package aaa.bbb.ccc.war;

    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.util.Properties;
    import org.apache.logging.log4j.LogManager;

    public class DBUtility
    {
        private static final org.apache.logging.log4j.Logger LOG = LogManager.getLogger("DBUtility");
        private static Connection connection = null;

        public static Connection getConnection()
        {
            if (connection != null)
            {
                return connection;
            }
            else
            {
                try
                {
                    Properties prop = new Properties();
                    InputStream inputStream = DBUtility.class.getClassLoader().getResourceAsStream("/config.properties");
                    prop.load(inputStream);
                    String driver = prop.getProperty("driver");
                    String url = prop.getProperty("url");
                    String user = prop.getProperty("user");
                    String password = prop.getProperty("password");
                    Class.forName(driver);
                    connection = DriverManager.getConnection(url, user, password);
                }
                catch (ClassNotFoundException e)
                {
                    LOG.error("____________________________getConnection____________________________ClassNotFoundException", e);
                }
                catch (SQLException e)
                {
                    LOG.error("____________________________getConnection____________________________SQLException", e);
                }
                catch (FileNotFoundException e)
                {
                    LOG.error("____________________________getConnection____________________________FileNotFoundException", e);
                }
                catch (IOException e)
                {
                    LOG.error("____________________________getConnection____________________________IOException", e);
                }

                return connection;
            }
        }
    }

  • 任务.java*
package aaa.bbb.ccc.war;

    public class Task
    {
        private int task_id;
        private String task_name;
        private String task_description;
        private String task_priority;
        private String task_status;

        public int getTaskId()
        {
            return task_id;
        }
        public void setTaskId(int taskId)
        {
            this.task_id = taskId;
        }

        public String getTaskName()
        {
            return task_name;
        }
        public void setTaskName(String taskName)
        {
            this.task_name = taskName;
        }

        public String getTaskDescription()
        {
            return task_description;
        }
        public void setTaskDescription(String taskDescription)
        {
            this.task_description = taskDescription;
        }

        public String getTaskPriority()
        {
            return task_priority;
        }
        public void setTaskPriority(String taskPriority)
        {
            this.task_priority = taskPriority;
        }

        public String getTaskStatus()
        {
            return task_status;
        }
        public void setTaskStatus(String taskStatus)
        {
            this.task_status = taskStatus;
        }

        @Override
        public String toString()
        {
            return "Task{" + "task_id=" + task_id + ", task_name=" + task_name + ", task_description=" + task_description + ", task_priority=" + task_priority + ", task_status=" + task_status + '}';
        }
    }

  • applicationContext.xml *
<?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
                               http://www.springframework.org/schema/beans/spring-beans.xsd
                               http://www.springframework.org/schema/mvc
                               http://www.springframework.org/schema/mvc/spring-mvc.xsd
                               http://www.springframework.org/schema/context
                               http://www.springframework.org/schema/context/spring-context.xsd">
        <context:component-scan base-package="aaa.bbb.ccc.war" />
        <mvc:annotation-driven>
            <mvc:message-converters>
                <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
            </mvc:message-converters>
        </mvc:annotation-driven>
        <mvc:default-servlet-handler/>
        <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"> 
            <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> 
            <property name="prefix" value="/jsp/" /> 
            <property name="suffix" value=".jsp" /> 
        </bean>    
        <mvc:resources mapping="/static/**" location="/static/" />
        <mvc:resources mapping="/webjars/**" location="/webjars/" />
        <mvc:resources mapping="/assets/**" location="/assets/" />
        <mvc:resources mapping="/resources/**" location="/resources/" />    
    </beans>

  • web.xml *
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
             version="3.1">
        <filter>
            <filter-name>charEncodingFilter</filter-name>
            <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
            <init-param>
                <param-name>encoding</param-name>
                <param-value>UTF-8</param-value>
            </init-param>
            <init-param>
                <param-name>forceEncoding</param-name>
                <param-value>true</param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>charEncodingFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
        <listener>
            <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
        </listener>    
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                WEB-INF/spring/applicationContext.xml
            </param-value>
        </context-param>
        <servlet>
            <servlet-name>appServlet</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>
                    WEB-INF/spring/applicationContext.xml           
                </param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>appServlet</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
        <welcome-file-list>
            <welcome-file>index.html</welcome-file>
            <welcome-file>index.htm</welcome-file>
            <welcome-file>index.jsp</welcome-file>
            <welcome-file>default.html</welcome-file>
            <welcome-file>default.htm</welcome-file>
            <welcome-file>default.jsp</welcome-file>
        </welcome-file-list>
    </web-app>

  • 配置属性 *
driver=org.apache.derby.jdbc.ClientDriver
    url=jdbc:derby://localhost:1527/taskmanager
    user=app
    password=app

  • log4j2.xml*
<?xml version="1.0" encoding="UTF-8"?>
    <Configuration status="warn" name="testLogEvent" packages="">
        <Appenders>
            <Console name="STDOUT" target="SYSTEM_OUT">
               <PatternLayout pattern="%-7p %d [%t] %c %x - %m%n"/>           
           </Console>
            <!-- writes log file to the tomee "logs" folder... -->       
            <File name="appLog" fileName="../logs/nggridtest.log">
                <PatternLayout>
                    <Pattern>%-7p %d [%t] %c %x - %m%n</Pattern>                
                </PatternLayout>
            </File>
            <Async name="Async">
                <AppenderRef ref="appLog"/>
            </Async>
        </Appenders>
        <Loggers>
            <Root level="DEBUG">
                <AppenderRef ref="STDOUT"/>  
                <AppenderRef ref="Async"/>                      
            </Root>
        </Loggers>
    </Configuration>

  • 使用Derby数据库 *
CREATE TABLE "TASK_LIST"
    (    
       "TASK_ID" INT not null primary key GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),   
       "TASK_NAME" VARCHAR(50),     
       "TASK_DESCRIPTION" VARCHAR(50),
       "TASK_PRIORITY" VARCHAR(100),
       "TASK_STATUS" VARCHAR(20),
       "TASK_START_TIME" TIMESTAMP,  
       "TASK_END_TIME" TIMESTAMP,
       "TASK_ARCHIVED" BOOLEAN 
    );

    //...NOTE: the task_id column value is auto-generated...
    insert into task_list (task_name, task_description, task_priority, task_status, task_start_time, task_end_time, task_archived) values('Gathering Requirement',    'Requirement Gathering',    'MEDIUM',   'ACTIVE', CURRENT TIMESTAMP, {fn TIMESTAMPADD(SQL_TSI_HOUR, 1, CURRENT_TIMESTAMP)}, false);
    insert into task_list (task_name, task_description, task_priority, task_status, task_start_time, task_end_time, task_archived) values('Application Designing',    'Application Designing',    'MEDIUM',   'ACTIVE', CURRENT TIMESTAMP, {fn TIMESTAMPADD(SQL_TSI_HOUR, 2, CURRENT_TIMESTAMP)}, false);
    insert into task_list (task_name, task_description, task_priority, task_status, task_start_time, task_end_time, task_archived) values('Implementation',           'Implementation',           'MEDIUM',   'ACTIVE', CURRENT TIMESTAMP, {fn TIMESTAMPADD(SQL_TSI_HOUR, 3, CURRENT_TIMESTAMP)}, false);
    insert into task_list (task_name, task_description, task_priority, task_status, task_start_time, task_end_time, task_archived) values('Unit Testing',             'Unit Testing',             'LOW',      'ACTIVE', CURRENT TIMESTAMP, {fn TIMESTAMPADD(SQL_TSI_HOUR, 4, CURRENT_TIMESTAMP)}, false);
    insert into task_list (task_name, task_description, task_priority, task_status, task_start_time, task_end_time, task_archived) values('Maintenance',              'Maintenance',              'LOW',      'ACTIVE', CURRENT TIMESTAMP, {fn TIMESTAMPADD(SQL_TSI_HOUR, 5, CURRENT_TIMESTAMP)}, false);


项目结构 *


wfveoks0

wfveoks01#

正如Lrossy所提到的,可能是对象还没有定义,所以在控制器或链接函数的开头(在get请求之前),定义它:
第一个月
那么,也许它需要一个轻推来应用范围?不太可能,因为$http知道这样做,但它可能有助于将其放入成功处理程序中:

if (!$scope.$$phase) {
  $scope.$apply();
}

字符串

相关问题