简体   繁体   中英

Simple angular project not working

can't seem to get the test.json data to output on my local.

Not sure if it's to do with the fact I'm running it locally or not.

Thanks :)

index.html

<!doctype html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
  </head>
  <body ng-app="testApp">

    <div class="main" ng-controller="MainController">
        <div class="container">
            <div ng-repeat="info in test">
                <p>{{ info.nm }}</p>
                <p>{{ info.cty }}</p>
                <p>{{ info.hse }}</p>
                <img ng-src="{{ info.cty }}">
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-2.2.4.min.js"   integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="   crossorigin="anonymous"></script>

    <!-- Include the AngularJS library -->
    <script  src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0/angular.min.js"></script>

    <!-- Modules -->
    <script src="js/app.js"></script>

    <!-- Controllers -->
    <script src="js/controllers/MainController.js"></script>

    <!-- Services -->
    <script src="js/services/servicetest.js"></script>

  </body>
</html>

app.js

var app = angular.module('testApp', ['']);

MainController.js

app.controller('MainController', ['$scope', 'test', function($scope, test) {
  test.success(function(data) {
    $scope.test = data;
  });
}]);

servicetest.js

app.factory('test', ['$http', function($http) {
  return $http.get('test.json')
            .success(function(data) {
              return data;
            })
            .error(function(err) {
              return err;
            });
}]);

test.json is in the same folder as servicetest.js.

Several mistakes are there in your code.

  1. You should not specify module dependency as blank( '' ) which would ask injector for '' and will throw an $injector error

      var app = angular.module('testApp', []); 
  2. Factory should return a object of methods like

     app.factory('test', ['$http', function($http) { var getData = function(){ return $http.get('test.json') } return { getData: getData } }]); 
  3. Utilize newly created factory method from controller.

      test.getData().then(function(response) { $scope.test = response.data; }); 

Can you try with

var app = angular.module('testApp', []);

instead of

var app = angular.module('testApp', ['']);

That array is meant, You could simply say for injecting various dependency.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM