【问题标题】:Binding does not work between view and controller绑定在视图和控制器之间不起作用
【发布时间】:2016-12-31 09:24:15
【问题描述】:

我刚开始用 Mean.js 开发,在 angular 部分有点问题。

我在 node 中创建了 api,可以使用配方模型进行基本的 crud。

现在我正在尝试显示现有食谱的列表。

控制器:

'use strict';

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

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

查看:

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

服务:

'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;
  }
]);

所以,当我在控制器中控制台记录 vm.recipe,然后查看异步调用是否会处理内容时,我会在 vm.recipes 中看到 2 个结果,这是正确的,因为我在 DB 中有 2 个结果。这种证明服务工作正常并加载数据。此外,它看起来在控制器中没问题,因为它会在那里检索数据。但是,这些数据不会加载到视图中,我不知道为什么。在配置中正确选择了视图。

有人知道吗?

【问题讨论】:

    标签: javascript angularjs meanjs


    【解决方案1】:

    请试试这个

    var vm = this;
    
    vm.recipes = RecipeService.query();
    

    尝试使用

    $scope.recipes = RecipeService.query();
    

    在控制器中

    在 html 中 在 采用 只有

    【讨论】:

    • 我们都是对的。我实际上找到了为什么这个 vm 示例不起作用并且它在 mean.js 示例模块中起作用。有一些标志可以将范围映射设置为 vm 属性。
    • @MichalTakáč 你指的是client.routes.js 文件中的controllerAs: 'vm' 吗?
    • @LukeKroon 不,我不是,那是错误。
    【解决方案2】:

    好的,不知道为什么它不能以这种形式工作,但我已经能够通过简单地将食谱放入 $scope 属性来使其工作。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-19
      • 2018-10-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多