首页 > 解决方案 > Angular JS 中是否有来自 React JS 的等价道具?

问题描述

我正在学习 angularJS,我想知道是否有像 react 一样的道具。更具体地说,一种添加我在另一个文件中定义的道具的方法。这将使我以 Angular 编码的网站更加高效,但我在 Angular 中找不到等价物。

标签: angularjsreactjsreact-props

解决方案


在 AngularJS 中有一种方法可以做类似的事情。它被称为指令。在您的情况下,您想创建一个restrict设置为的指令'E'
'E'告诉编译器它将是生成的 HTML 中的一个元素。

angular.module('scopeDirective', [])
.controller('app', ['$scope', function($scope) {
  $scope.naomi = { name: 'Uriel', address: '1600 Amphitheatre' };
  $scope.igor = { name: 'Bitton', address: '123 Somewhere' };
}])
.directive('customer', function() {
  return {
    restrict: 'E',
    scope: {
      customerInfo: '=info'
    },
    templateUrl: 'customer.html'
  };
});

之后的scope对象restrict定义了您希望该指令接受的各种属性。这类似于 React 中 props 的工作方式。在该对象中,您可以看到customerInfo哪个对应于指令的隔离范围属性。该值(=info)告诉$compile绑定到 info 属性。
映射到该templateUrl指令的 HTML。

使用上述指令将如下所示:

<div ng-controller="app">
  <customer info="uriel"></customer>
  <hr>
  <customer info="bitton"></customer>
</div>

请参阅Directives上的 AngularJS 文档。

注意:与其尝试在 AngularJS 中做一些类似于在 React 或任何其他框架/库中做事的事情,我建议您不要接受当前框架的功能并按原样使用它而不尝试比较实现类似的事情,因为这可能会导致挫败感。

我希望您发现此答案对您的需求有用。


推荐阅读