我正在学习 angularJS,我想知道是否有与 React 中类似的 props。更具体地说,是一种添加我在另一个文件中定义的 Prop 的方法。这将使我用 Angular 编码的网站更加高效,但我在 Angular 中找不到等效的东西。
最佳答案
有一种方法可以在 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'
};
});
restrict
之后的 scope
对象定义了您希望该指令接受的各种属性。这类似于 React 中 props 的工作方式。在该对象中,您可以看到与指令的隔离范围属性相对应的 customerInfo
。值 (=info)
告诉 $compile
绑定(bind)到 info 属性。
templateUrl
映射到该指令的 HTML。
使用上述指令将如下所示:
<div ng-controller="app">
<customer info="uriel"></customer>
<hr>
<customer info="bitton"></customer>
</div>
请参阅 Directives 上的 AngularJS 文档.
NOTE: Instead of trying to do something in AngularJS that is similar to how you do things in React or any other framework/library, I would suggest you do not instead embrace the current framework's capability and use it as is without trying to compare way of achieving similar things as this can lead to frustration down the road.
我希望您发现这个答案对您的需求有用。
关于angularjs - Angular JS 中是否有与 React JS 中的 props 相当的东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58810144/