Issue
I am learning angularJS and I was wondering if there is the equivalent of props like there is in react. More specifically, a way to add with props that I define in another file. It would make the website I'm coding in angular much more efficient but I can't find the equivalent in Angular.
Solution
There is a way to do something similar in AngularJS. It is called Directives. In your case you want to create a directive with restrict set to 'E'.
'E' tells the compiler that it will be an element in the generated 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'
};
});
The scope object after restrict defines the various attributes you would want this directive to accept. This is similar to how props work in React. In that object, you can see customerInfo which corresponds to the directive's isolate scope property. The value (=info) tells $compile to bind to the info attribute.
The templateUrl maps to the HTML for this directive.
Using the above directive will look something like below:
<div ng-controller="app">
<customer info="uriel"></customer>
<hr>
<customer info="bitton"></customer>
</div>
Kindly refer to the AngularJS docs on Directives.
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.
I hope you find this answer useful for your needs.
Answered By - codejockie
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.