angular删除节点_节点和Angular To-Do应用程序:控制器和服务

angular删除节点

In the last part of our Node and Angular To-Do App Series, we played mostly on the Node side of things dealing with application organization and structure. Today we will be handling the Angular side of things.

在我们的Node and Angular To-Do App Series的最后一部分中,我们主要在Node方面进行与应用程序组织和结构有关的事情。 今天,我们将处理事物的角度方面。

Here is what we'll be doing:

这是我们要做的:

  • Organizing: Moving our Angular $http elements into a separate services file.

    组织 :将Angular $ http元素移动到一个单独的服务文件中。
  • Services: Creating a service for our Todos

    服务 :为我们的待办事项创建服务
  • Controllers: Moving our entire controller into its own file so its not a global controller.

    控制器 :将整个控制器移到其自己的文件中,因此它不是全局控制器。
  • Upgrading our app to Angular 1.2.4 from 1.0.8 (just link to the new version)

    将我们的应用程序从1.0.8升级到Angular 1.2.4(只需链接到新版本)
  • Fixing a little bug where a user could hold down the enter button keep creating the same Todo

    修复了一个小错误,使用户可以按住Enter键继续创建相同的Todo

This entire article will be on the frontend of our application. We used Node to create our backend RESTful API and that will not change. This is the beauty of creating an API. Frontend and backend remain independent of each other. This will also be great in the future if we ever want to use our API to build more than just a website. Maybe we would want to create a mobile app or something else in the future.

整篇文章将在我们应用程序的前端。 我们使用Node创建了后端RESTful API,并且不会改变。 这是创建API的美妙之处。 前端和后端保持彼此独立。 如果我们想使用我们的API来构建不仅仅是一个网站,那么将来这也将很棒。 也许将来我们想创建一个移动应用程序或其他东西。

Let's get started with some basic organization for our app. Nowhere near as extensive as what we did for Node. We'll just be moving our javascript files and Angular modules into separate files.

让我们从应用程序的一些基本组织开始。 没有像我们对Node所做的那样广泛。 我们将把javascript文件和Angular模块移动到单独的文件中。

整理我们的申请 (Organizing Our Application)

Before, we had all of our Angular code in one core.js file. This isn't what we want moving forward. We want our application to be modular so that our controller and all of our $http requests are in their own files.

以前,我们将所有Angular代码都放在一个core.js文件中。 这不是我们想要前进的方向。 我们希望我们的应用程序是模块化的,以便我们的控制器和所有$ http请求都在它们自己的文件中。

Why modular? Having all of your functionality in different modules helps for many reason.

为什么模块化? 将您的所有功能放在不同的模块中有很多帮助。

  • The overall layout of your application is easier to understand.

    您的应用程序的整体布局更容易理解。
  • You can see how the parts work together since modules have to be injected before use.

    您可以看到部件如何协同工作,因为必须在使用前注入模块。
  • Code is reusable since all of the necessary functionality is contained inside the module.

    由于所有必需的功能都包含在模块内部,因此代码可重复使用。
  • Testing your code is much easier

    测试代码要容易得多

申请文件 (Application Files)

For this tutorial, we will only be looking in our applications public folder since that's where all the frontend code lives.

在本教程中,我们将简单的看在我们的应用程序public文件夹,因为这就是所有的前端代码生命。

Here is how we want our new public file structure to look.

这就是我们希望新的公共文件结构看起来的样子。

-- public
-------- js
-------------- controllers
--------------------- main.js
-------------- services
--------------------- todos.js
-------------- core.js 
-------- index.html

Let's go ahead and open up our index.html file and load up the files we need. We will also upgrade our Angular 1.0.8 to 1.2.4.

让我们继续打开我们的index.html文件并加载所需的文件。 我们还将Angular 1.0.8升级到1.2.4。

<!-- index.html -->
...
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.min.js"></script><!-- load angular 1.2.4 -->

    <script src="js/controllers/main.js"></script> <!-- load up our controller -->
    <script src="js/services/todos.js"></script> <!-- load our todo service -->
    <script src="js/core.js"></script> <!-- load our main application -->

</head>
...

There are many changes from 1.0.8 to 1.2.x, but they don't seem to affect our app. If you want to see a full changelog, visit the migration guide.

从1.0.8到1.2.x有很多更改,但它们似乎并不影响我们的应用程序。 如果您想查看完整的变更日志,请访问迁移指南

待办事项服务js / services / todos.js (To-do Service js/services/todos.js)

Let's create our service. The to-do service is meant to interact with our Node API. We want to have all the code to get, create, or delete a to-do inside our service. This ensures that we can test this code separate of our overall application. Let's get all that $http code out of our main application file (core.js).

让我们创建我们的服务。 待办事项旨在与我们的Node API进行交互。 我们希望在我们的服务中拥有获取创建删除待办事项的所有代码。 这确保了我们可以将这些代码与整个应用程序分开进行测试。 让我们从主应用程序文件(core.js)中获取所有$ http代码。

// js/services/todos.js
angular.module('todoService', [])

    // super simple service
    // each function returns a promise object 
    .factory('Todos', function($http) {
        return {
            get : function() {
                return $http.get('/api/todos');
            },
            create : function(todoData) {
                return $http.post('/api/todos', todoData);
            },
            delete : function(id) {
                return $http.delete('/api/todos/' + id);
            }
        }
    });

That's all there is to it. We have defined our service using .factory with three different functions. get, create and delete will all return promise objects that we can use in our controller.

这里的所有都是它的。 我们使用具有三个不同功能的.factory定义了服务。 getcreatedelete将全部返回可以在控制器中使用的promise对象

Declaring Services There are many different ways to declare a service (.service, .factory and .provider). To understand the differences a little better, here's a Stackoverflow question and answer.

声明服务有许多不同的方式申报服务( .service.factory.provider )。 为了更好地理解这些差异,这里有一个Stackoverflow问答

待办事项主控制器js / controllers / main.js (To-do Main Controller js/controllers/main.js)

Now that we have our service, let's create our Angular module for our controller. We will be moving most of the code out of core.js into our controller file.

现在我们有了服务,让我们为控制器创建Angular模块。 我们将把大部分代码从core.js到我们的控制器文件中。

// js/controllers/main.js

angular.module('todoController', [])

    .controller('mainController', function($scope, $http) {
        $scope.formData = {};

        // when landing on the page, get all todos and show them
        $http.get('/api/todos')
                .success(function(data) {
                        $scope.todos = data;
                })
                .error(function(data) {
                        console.log('Error: ' + data);
                });

        // when submitting the add form, send the text to the node API
        $scope.createTodo = function() {
                $http.post('/api/todos', $scope.formData)
                        .success(function(data) {
                                $scope.formData = {}; // clear the form so our user is ready to enter another
                                $scope.todos = data;
                        })
                        .error(function(data) {
                                console.log('Error: ' + data);
                        });
        };

        // delete a todo after checking it
        $scope.deleteTodo = function(id) {
                $http.delete('/api/todos/' + id)
                        .success(function(data) {
                                $scope.todos = data;
                        })
                        .error(function(data) {
                                console.log('Error: ' + data);
                        });
        };

    });

We have moved our controller code out of core.js. While we now have our controller and service in their own modules, they won't be able to work together until we inject them into our main application module.

我们已经将控制器代码从core.js 。 现在,我们已经将控制器和服务放在自己的模块中,但是除非将它们注入到主应用程序模块中,否则它们将无法协同工作。

使所有模块协同工作js / core.js (Getting All Modules Working Together js/core.js)

To get everything working together, we just have to load our controller and services (we did that already in our index.html), and then inject our controller and service into the main module.

为了使所有功能协同工作,我们只需要加载控制器和服务(我们已经在index.html中进行了此操作),然后将控制器和服务注入到主模块中。

core.js file from the root directory into the core.js文件从根目录移动到 js folder. This ensures that all our javascript code will be located in the same location. js文件夹中。 这样可以确保我们所有JavaScript代码都位于同一位置。

Here is the entire code for our new core.js.

这是我们新的core.js完整代码

// js/core.js

angular.module('scotchTodo', ['todoController', 'todoService']);

That's it! You can see how easy that is to read. We have our main module scotchTodo and then we inject our controller and service.

而已! 您会看到它很容易阅读。 我们有主要模块scotchTodo ,然后注入控制器和服务。

Now that our application is set to work together again, we need to use

现在我们的应用程序已设置为可以再次一起工作,我们需要使用

在我们的控制器中使用我们的服务 (Using Our Service in Our Controller)

We have linked everything but we are not using our new service yet. Let's inject that into our controller and use it!

我们已链接了所有内容,但尚未使用新服务。 让我们将其注入到控制器中并使用它!

// js/controllers/main.js
angular.module('todoController', [])

    // inject the Todo service factory into our controller
    .controller('mainController', function($scope, $http, Todos) {
        $scope.formData = {};

        // GET =====================================================================
        // when landing on the page, get all todos and show them
        // use the service to get all the todos
        Todos.get()
            .success(function(data) {
                $scope.todos = data;
            });

        // CREATE ==================================================================
        // when submitting the add form, send the text to the node API
        $scope.createTodo = function() {

            // validate the formData to make sure that something is there
            // if form is empty, nothing will happen
            // people can't just hold enter to keep adding the same to-do anymore
            if (!$.isEmptyObject($scope.formData)) {

                // call the create function from our service (returns a promise object)
                Todos.create($scope.formData)

                    // if successful creation, call our get function to get all the new todos
                    .success(function(data) {
                        $scope.formData = {}; // clear the form so our user is ready to enter another
                        $scope.todos = data; // assign our new list of todos
                    });
            }
        };

        // DELETE ==================================================================
        // delete a todo after checking it
        $scope.deleteTodo = function(id) {
            Todos.delete(id)
                // if successful creation, call our get function to get all the new todos
                .success(function(data) {
                    $scope.todos = data; // assign our new list of todos
                });
        };
    });

As you can see, the code looks very similar to how it used to be. That is because the main thing we did was move the old $http code outside of our controller and into our service. The service will return a promise object so we can use the data using .success promise.

如您所见,该代码看起来与以前非常相似。 那是因为我们要做的主要事情是将旧的$http代码移到我们的控制器之外并移到我们的服务中。 该服务将返回一个承诺对象,所以我们可以通过使用数据.success承诺。

结论 (Conclusion)

Now we have organized the frontend of our application. We have separated controller and service and gotten our modules to work together via injection.

现在,我们已经组织了应用程序的前端。 我们将控制器服务分开,并通过注入使我们的模块一起工作。

Our application should work the exact same as before, but when we eventually want to grow our application, it will be far more scalable and testable.

我们的应用程序应该与以前完全一样地工作,但是当我们最终想要扩展我们的应用程序时,它将具有更大的可伸缩性和可测试性。

In the next few tutorials, we will be doing more frontend work and adding filtering and searching to our application. We will also be working on the backend again and adding Node authentication with Passport.

在接下来的几篇教程中,我们将做更多的前端工作,并为我们的应用程序添加过滤和搜索功能。 我们还将再次在后端工作,并使用Passport添加Node身份验证。

翻译自: https://scotch.io/tutorials/node-and-angular-to-do-app-controllers-and-services

angular删除节点

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值