Michal Takáč
Michal Takáč

Reputation: 1055

Binding does not work between view and controller

I just started to develop in Mean.js and have a bit of problem on angular part.

Ive created api in node which can do basic crud with recipe model.

Now Im trying to display a list of existing recipes.

Controller:

'use strict';

angular.module('recipe').controller('RecipeController', ['$scope', 'RecipeService',
  function ($scope, RecipeService) {
    // Recipe controller logic
    var vm = this;

    vm.recipes = RecipeService.query();
  }
]);

View:

<section data-ng-controller="RecipeController">
  <div data-ng-repeat="recipe in vm.recipes">
    {{recipe.title}}
  </div>
</section>

Service:

'use strict';

angular.module('recipe').factory('RecipeService', [ '$resource',
  function ($resource) {
    // Recipe service logic
    var Recipe = $resource('api/recipes/:recipeId', {
      recipeId: '@_id'
    }, {
      update: {
        method: 'PUT'
      }
    });

    angular.extend(Recipe.prototype, {
      createOrUpdate: function () {
        var recipe = this;
        return createOrUpdate(recipe);
      }
    });

    function createOrUpdate(recipe) {
      if(recipe._id) {
        return recipe.$update(onSuccess, onError);
      } else {
        return recipe.$save(onSuccess, onError);
      }

      function onSuccess(recipe) {

      }

      function onError(errorResponse) {
        var error = errorResponse.data;
        handleError(error);
      }
    }

    function handleError(error) {
      console.log(error);
    }

    // Public API
    return Recipe;
  }
]);

So, when I console log the vm.recipe in controller and then take a look after async call will handle stuff, I will see 2 results in vm.recipes, which is correct since I have 2 results in the DB. This kinds of proves that service is working fine and load the data. Also, it looks like in controller its okay, since it will retrieve data there. But, those data will not be loaded into view, and I have no idea why. The view is selected correctly in the config.

Have anyone any idea?

Upvotes: 0

Views: 46

Answers (2)

Abhishek Priyadarshi
Abhishek Priyadarshi

Reputation: 571

please try this

at the place of

var vm = this;

vm.recipes = RecipeService.query();

try to use

$scope.recipes = RecipeService.query();

in controller

and in html at place of use only

Upvotes: 1

Michal Tak&#225;č
Michal Tak&#225;č

Reputation: 1055

Ok, did not find out why it does not work in this form, but Ive been able to get it working by simply putting recipes into $scope property.

'use strict';

angular.module('recipe').controller('RecipeController', ['$scope', 'RecipeService',
  function ($scope, RecipeService) {
    // Recipe controller logic
    $scope.recipes = RecipeService.query();
  }
]);

Upvotes: 0

Related Questions