0

Sorry, I'm new to AngularJs. I made an application that receives data from the service, and displays it in main.html. Before that, I used $scope. And everything worked. But with as controller syntax, the application does not work.

main.html:

<div ng-repeat="item in main.newItems">
 <img src="{{item.min_img}}">
 <div>{{item.name}}</div>
</div>

app.js

var shopApp = angular.module("shopApp",["ngRoute"]);

shopApp.config(['$routeProvider',function($routeProvider){
        $routeProvider.when('/main',{
                templateUrl:'/main.html',
                controller:"mainCtrl",
                controllerAs:"main"});
}]);

shopApp.controller("mainCtrl",function(newItemsFactory){
    this.newItems=newItemsFactory.getNewItems().then(function success(response) {
        this.newItems=response.data;
    });
});

shopApp.factory('newItemsFactory',function($http){
    return{
        getNewItems:function(){
            return $http({method: 'GET', url: 'newItems.json'});    
        }
    }
});

newItems.json

[
{"min_img:1.png",name:"first"},
{"min_img:2.png",name:"second"},,
{"min_img:3.png",name:"third"},
]

Sorry for my bad Engish and Thank.

  • `this.newItems=response.data;` I do believe in this case the `this` is in reference to the function it's inside. When using controller as it's best to define a variable at the top of the controller like `var main = this;` then you can change it to `main.newItems = blah blah` – George May 08 '17 at 08:01
  • try use `var vm = this` instead of `this` in controller – Hadi J May 08 '17 at 08:01

1 Answers1

2

There is a wrong assignment and wrong this in your controller. The common pattern is to capture this in a variable vm:

shopApp.controller("mainCtrl",function(newItemsFactory){
  var vm = this;
  newItemsFactory.getNewItems().then(function success(response) {
    vm.newItems = response.data;
  });
});
hansmaad
  • 18,417
  • 9
  • 53
  • 94