0

I'm new to angularJS, I'm trying to iterate through object properties mentioned in controller function using ng-repeat, but no success!

   <body ng-app="myApp">
          <div ng-controller="myCtrl">

<ul>

 <li ng-repeat="dish in myCtrl.dishes">{{ dish.name + ', ' + dish.age + ', ' + dish.job }}</li>

 </ul>

 </div>
 <script>
  var app=angular.module('myApp',[]);
      app.controller('myCtrl',function(){
            var dishes=[
                         {
                           name:'nag',
                            age:'23',
                           job:'UI Developer'

                          },
                        {
                            name:'Manu',
                             age:'30',
                              job:'SE'

                         }

                        ];

                       this.dishes = dishes;
                    });

     </script>

2 Answers 2

1

You should use this instead of var, in controller.

Also your view should be,

<div ng-app="myApp" ng-controller="myCtrl as ctrl">
      <ul>
     <li ng-repeat="dish in ctrl.dishes">

DEMO

var app=angular.module('myApp',[]);
app.controller('myCtrl',function($scope){
this.dishes=[
{
 name:'nag',
 age:'23',
 job:'UI Developer'
},
{
 name:'Manu',
 age:'30',
 job:'SE'
}
];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl as ctrl">
  <ul>
 <li ng-repeat="dish in ctrl.dishes">{{ dish.name + ', ' + dish.age + ', ' + dish.job }}</li>
 </ul>
</div>

Sign up to request clarification or add additional context in comments.

8 Comments

can't we do it without using scope object?
You can do it by using this.dieshes = yourarray. and then in view ctr.dishes
and yes..that's what i wanted to do. I've assigned using "this" now, please check it once again and tel me where i'm goin wrong
one doubt. why are we using alias for controller function? and when i removed it, it simply didn't work !
you should have that, if you are not using $scope variable. toddmotto.com/digging-into-angulars-controller-as-syntax
|
0

using $scope. be careful using 'this', because you can lose the context into the functions.

var app=angular.module('myApp',[]);
app.controller('myCtrl',['$scope',function($scope){
$scope.dishes=[{name:'nag',age:'23',job:'UI Developer'},
               {name:'Manu',age:'30',job:'SE'}];
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <ul>
 <li ng-repeat="dish in dishes">{{ dish.name + ', ' + dish.age + ', ' + dish.job }}</li>
 </ul>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.