首页 > 解决方案 > 在这种情况下,我是否需要在 angularjs 中手动管理范围?

问题描述

我正在(重新)学习 angularjs,因为我需要将一些现有代码迁移到另一个框架。

我有一个控制器,负责管理在表格中呈现的保存的收藏夹列表。收藏夹被保存到 mongodb 集合中。它看起来像这样:

export const favoritesController = ($scope, getFavorites, removeFavorites) => {
    getFavorites.then(favs => {
        $scope.favorites = favs;
    });

    // Called when a button is clicked
    // to remove selected favorites from a table.
    $scope.removeFavorite = ($event) => {
        let ids = [];
        $("#favorites input:checked").each((i, el) => {
            ids.push(parseInt(el.value));
        });
        removeFavorites(ids);

        // I know, we should ensure the
        // scope management occurs only 
        // when and if the
        // favs were successfully deleted. 
        $scope.favorites = $scope.favorites.filter(
            favorite => {
                return !ids.includes(favorite.id);
            });
   };
}

如果我只是调用该服务从 db ( removeFavorites) 中删除收藏夹,则范围不受影响,因此收藏夹不会从 UI 中的显示表中删除。我还必须从$scope. 那是对的吗?是否有其他方法可以连接范围变量和数据库上的操作,或者我是否正确必须手动完成?

标签: javascriptangularjssingle-page-application

解决方案


推荐阅读