Angularjs 1.5 - CRUD页面和组件 [英] Angularjs 1.5 - CRUD pages and Components

查看:80
本文介绍了Angularjs 1.5 - CRUD页面和组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个小型Angularjs 1.5项目中工作,我很新。

I'm working in a small Angularjs 1.5 project and I'm quite new.

我必须创建一个对象或编辑现有对象,模板是同样,逻辑的唯一区别是在更新的情况下调用http服务进行数据检索。
我使用ngRoute。
如何在两个操作中使用相同的组件?

I have to create an object or edit an existing object and the template is the same, the only difference in the logic is the call to an http service for data retrieve in case of update. I use ngRoute. How can I do to use the same component for both operations ?

编辑

JS COMPONENT CODE

JS COMPONENT CODE

angular.
module('editProject').
    component('editProject', {
        templateUrl: 'app/edit-project/edit-project.template.html',
        controller:['$http','$routeParams', function EditProjectController($http,$routeParams) {
            var self=this;
            $http.get('rest/projects/' + $routeParams.id ).then(function(response) {
              console.log(JSON.stringify(response.data));
              self.project = response.data;
            });


        }
  ]
  });

ROUTE CONFIG

angular.
  module('myApp').
   config(['$locationProvider', '$routeProvider',
   function config($locationProvider, $routeProvider) {
      $locationProvider.hashPrefix('!');

      $routeProvider.
    when('/projects', {
      template: '<project-list></project-list>'
    }).
    when('/projects/:id', {
      template: '<project-detail></project-detail>'
    }).
    when('/projects/edit/:id', {
        template: '<edit-project></edit-project>'
      }).
    when('/projects/new', {
        template: '<edit-project></edit-project>'
    }).  
    otherwise('/projects');
}
 ]);


推荐答案

1。快速修复



如果定义了 $ routeParams.id param,则简单的解决方案是使用条件检查,如果是,那么它需要一个请求来提供项目信息,否则不需要。

1. Quick fix

Simple solution would be using a conditional checking if the $routeParams.id param is defined, if so, then it need a request to feed the project informations, otherwise not.

if($routeParams.id){
    $http.get('rest/projects/' + $routeParams.id ).then(function(response) {
        console.log(JSON.stringify(response.data));
        self.project = response.data;
    });
}



2。组件路由器



尽管前面的解决方案看起来简单实用,但它可能不是最好的。一个propper解决方案是为每个路由使用一个单独的组件,但您可以重用它的表单部分。此外,假设您正在构建一个完整的基于组件的应用程序,您应该使用 ngComponentRoute 而不是 ngRoute

.component('app', {
  template: '<ng-outlet></ng-outlet>',
  $routeConfig: [
    {path: '/projects', name: 'Projects', component: 'projectList', useAsDefault: true},
    {path: '/projects/:id', name: 'Project Detail', component: 'projectDetail' },
    {path: '/projects/edit/:id', name: 'Edit Project', component: 'editProject' },
    {path: '/projects/new', name: 'New Project', component: 'newProject' }
  ]
});

然后你可以创建一个项目编辑器组件,并在编辑和新项目页面上重复使用它只需添加< project-editor-form project ={}on-save =$ ctrl.mySave()>< / project-editor-form> 。例如:

Then you can create a project editor component and reuse it on both edit and new project page by just adding <project-editor-form project="{}" on-save="$ctrl.mySave()"></project-editor-form>. For example:

.component('projectEditorForm', {
    template:
      'Project Name: <input type="text" ng-model="$ctrl.project.name">' +
      '<button ng-click="$ctrl.onSaveProject($ctrl.project)">Save</button>',
    bindings: {
        project: '<',
        onSave: '&'
    },
    controller: function () {
        var $ctrl = this;
        $ctrl.onSaveProject = function (project) {
            // general save logic goes here
            // if you want to reuse this too
            // then emit the on save for onSave binding
            $ctrl.onSave($ctrl.project);
        }
    },
  })

.component('editProject', {
    template:
      '<project-editor-form project="$ctrl.project" on-save="$ctrl.mySave()">' + 
      '</project-editor-form>',
    bindings: {
        project: '<',
        onSave: '&'
    },
    controller: function ($http) {
        var $ctrl = this;

        // consider using a Service to do such task
        // instead of request directly from the controller
        $http.get('rest/projects/' + $routeParams.id).then(function(response) {
            $ctrl.project = response.data;
        });

        $ctrl.mySave = function (project) {
            // save logic here
        }
    },
  })



3。 ngRoute with resolve



另一种不依赖 ngComponentRoute 的方法是使用route resolve属性,它是使用组件作为路由模板非常有用。您将路径中的resolve属性添加到项目中,然后绑定到表单组件。

3. ngRoute with resolve

Another approach that doesn't deppend on ngComponentRoute, is to use the route resolve property, it's very usefull when using component as route template. You add a resolve property to your route, that would be the project, and bind to your form component.

$routeProvider
  .when('/projects/edit/:id', {
    template: '<project-editor-form project="$resolve.project"></project-editor-form>',
    resolve: {
      project: function ($route, $q) {
        var id = $route.current.params.id;
        // again, consider using a service instead
        return $http.get('rest/projects/' + id).then(function (response) {
          return response.data;
        });
      }
    }
  })
  .when('/projects/new', {
    template: '<project-editor-form project="$resolve.project"></project-editor-form>',
    resolve: {
      project: {
        id: 0,
        name: ''
      }
    }
  })

这篇关于Angularjs 1.5 - CRUD页面和组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆