【问题标题】:how angular component, service and controller works角度组件、服务和控制器如何工作
【发布时间】:2016-09-02 03:08:34
【问题描述】:

我是 Angular 新手,并试图了解服务、组件和控制器的工作原理。

假设我有以下几点:

服务文件:products.service.js

 'use strict';

 angular.module('myApp.products')
 .factory('ProductService', function () {

     var products = [
            {_id: 1, title: 'Product 1', price: 123.45, quantity:10, description:'Some description 1'},
            {_id: 2, title: 'Product 2', price: 123.45, quantity:10, description:'Some description 2'},
            {_id: 3, title: 'Product 3', price: 123.45, quantity:10, description:'Some description 3'},
            {_id: 4, title: 'Product 4', price: 123.45, quantity:10, description:'Some description 4'},
            {_id: 5, title: 'Product 5', price: 123.45, quantity:10, description:'Some description 5'}
     ];

     return {
          alllProducts: function () {
              return products;
          }
     };
});

控制器文件:products.controller.js

 'use strict';
 (function(){

          class ProductsComponent {
               constructor() {
                   // how should i connect them here like below?
                   // this.products = ProductService.allProducts();
               }
          }

          angular.module('myApp')
               .component('products', {
                   templateUrl: 'app/products/products.html',
                    controller: ProductsComponent
               });

 })();

我正在使用 generator-angular-fullstack。如何连接控制器构造函数中的所有产品并在模板中显示它们?

谢谢

【问题讨论】:

    标签: angularjs controller components


    【解决方案1】:

    你已经很接近了,你只需要将 ProductService 注入到构造函数中:

    class ProductsComponent {
        constructor(ProductService) {
            this.products = ProductService.allProducts();
        }
    }
    

    google 上有数百种关于控制器、服务、指令的解释。他们中的许多人将使用 ES5 语法。组件是一种更具体的指令类型 - 请参阅the docs。

    简而言之,尽管服务控制您的应用程序数据,但控制器的唯一职责是将这些数据公开给视图。每当 Angular 实例化一个控制器时,它都会为它提供一个由this 引用的范围(至少,一旦控制器完成实例化)。

    组件是您视图的一部分。您在 html 视图模板中使用非驼峰式版本,此处为 <products></product>,并且 angular 将其替换为您的模板,并将控制器/控制器范围附加到视图的该部分。您可以在 products.html 模板中消费产品(例如使用<div ng-repeat="product in products>{{product.title}}></div>")。

    【讨论】:

    • 谢谢,这对我来说更有意义。如果我需要访问 stateParams,我应该像这样注入它:constructor(ProductService, $stateParams)?
    • 没错,只要在模块系统中注册,就可以在controller/component/directive/services等声明中注入。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-04
    • 2016-12-29
    • 2015-01-25
    • 2015-08-17
    • 2013-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多