2017-01-22 5 views
0

Что не так в моем коде? он не работает должным образомЧто не так в следующем коде angularjs

Моя .html выглядит страница Я начальный уровень кодировщик и имеют следующие коды:

<!DOCTYPE html> 
    <html ng-app="myApp"> 
    <head> 
    <meta charset="ISO-8859-1"> 
    <title>Index</title> 
    <script type="text/javascript" src="/scripts/angular.js"></script> 
     <script type="text/javascript"> 
     alert("in script"); 
     var app = angular.module("myApp", []); 
     app.controller("myCtrl", function($scope , $http) { 
      refreshData(); 

      function refreshData(){ 
       alert("function called"); 
       $http({ 
        alert("get all countries"); 
        method: 'GET', 
        url:'http://localhost:8081/SpringWithAngularJs/rest/countries.json' 
         }).success(function(data) 
          { 

          $scope.posts = data; 

          }); 
      } 
      $scope.form = { 
        countryName : "pp", 
        population : "1000" 
         }; 
      $scope.add=function(){ 
       $http({ 
        alert("add countries"); 
        method: 'POST', 
        url:'http://localhost:8081/SpringWithAngularJs/rest/countries/create/'+$scope.form.countryName+'/'+$scope.form.population 
        }).success(function(data){ 
         alert("Country Added"); 
         refreshData(); 
         }); 
       } 
      $scope.remove=function(data){ 
       $http({ 
        alert("delete countries"); 
        method: 'DELETE', 
        url:'http://localhost:8081/SpringWithAngularJs/rest/countries/delete/'+data 
        }).success(function(data){ 
         alert('Country Deleted'); 
         refreshData(); 
         }); 
      } 
     }); 
     </script> 
     </head> 
    <body ng-controller="myCtrl"> 
    <h1>Country List</h1> 
     <table border=""> 
      <thead> 
       <tr> 
        <th>Country Id</th> 
        <th>Country Name</th> 
        <th>Country Population</th> 
        <th>Action</th> 
       </tr> 
      </thead> 

      <tr ng-repeat="c in posts"> 
       <td>{{c.countryId}}</td> 
       <td>{{c.countryName}}</td> 
       <td>{{c.population}}</td> 
       <td><button ng-click="remove{$index}">Remove</button></td> 
      </tr> 
     </table> 

     <h1>Add Country</h1> 
     <table> 
      <tr> 
       <td>Country Name:</td> 
       <td><input type="text" ng-model="form.countryName"/></td> 
      </tr> 

      <tr> 
       <td>Country Population:</td> 
       <td><input type="text" ng-model="form.population"/></td> 
      </tr> 

      <tr> 
       <td><button type="submit" ng-click="add()">Add</button></td> 
      </tr> 

     </table> 

    </body> 
    </html> 

мой контроллер выглядит следующим образом: При запуске страницы HTML даже не оповещающие функции из javascript работает. Почему это происходит?

package com.cg.springwithangularjs.controllers; 

import java.util.List; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.ui.Model; 
import org.springframework.web.bind.annotation.PathVariable; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.bind.annotation.RestController; 

import com.cg.springwithangularjs.dtos.Country; 
import com.cg.springwithangularjs.exceptions.CountryException; 
import com.cg.springwithangularjs.services.CountryService; 

@RestController 
public class CountryFrontController { 
    @Autowired 
    CountryService countryService; 

    @RequestMapping(value="/countries",method=RequestMethod.GET,headers="Accept=application/json") 
    public List<Country> getallCountries(Model model){ 
     System.out.println("in function"); 
     try { 
      return countryService.getAllCountries(); 
     } catch (CountryException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     return null; 
    } 

    @RequestMapping(value="/countries/create/{name}/{popu}",method=RequestMethod.POST,headers="Accept=application/json") 
    public List<Country> addCountry(@PathVariable String name , @PathVariable String popu){ 
     Country country = new Country(); 
     country.setCountryName(name); 
     country.setPopulation(popu); 

     try { 
      countryService.addCountry(country); 
      return countryService.getAllCountries(); 
     } catch (CountryException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     return null; 
    } 

    @RequestMapping(value="/countries/delete/{id}",method=RequestMethod.DELETE,headers="Accept=application/json") 
    public List<Country> deleteCountry(@PathVariable String id){ 
     try { 
      countryService.delete(id); 
      return countryService.getAllCountries(); 
     } catch (CountryException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     return null; 
    } 
} 
+0

Can _you_ сообщите нам, что не так !? Любая консольная ошибка? –

+0

На самом деле я пытаюсь запустить свое первое приложение angularjs с весной. Я новичок, поэтому я не знаю об этом, и после запуска страницы .html написанный javascript не работает. @MatthewCawley – Girjesh

+0

попытайтесь удалить предупреждение() из объекта конфигурации в трех ваших сервисах http, чтобы они выглядели например $ http ({method: 'GET', url: '/someUrl'}).success ... – darron614

ответ

0

Удалить предупреждение() из объекта конфигурации в трех ваших $ HTTP услуг, так что они выглядят как $http({method: 'GET', url: '/someUrl'}).success ...

Также попытаться изменить вызов функции удалить из:

<td><button ng-click="remove{$index}">Remove</button></td> 

до:

<td><button ng-click="remove($index)">Remove</button></td> 
+0

Теханы работали. спасибо Не могли бы вы рассказать мне, как проверить поля в данной форме html. Валидации, как и название страны, должны быть необходимы, а численность населения должна быть численной @ darron614 – Girjesh

Смежные вопросы