Reputation: 429
So I've been using one controller one view, and using only Directives for parts that I want to use repeatedly.
Now Im going for an interview and I am asked to learn about component, which I never know existed. I'm trying to replace directive with it but can't even pass a simple object into the component from the parent controller.
app.js
var myApp= angular.module('bigMoveApp', ['ngRoute', 'testerModule']);
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'app/Views/main.html',
controller: 'ctrlMain'
}).
otherwise({
redirectTo: '/'
});
}]);
ctrlMain.js
myApp.controller('ctrlMain', ['$scope', function ($scope) {
//code
$scope.paragraphToWrite = { text: "let's write something" };
//code
}])
main.html
<div id="main-body-wrapper">
<...>
<paragraph-Component obj="paragraphToWrite"></paragraph-Component>
<...>
</div>
paragraphComponent.js
function paragraphController($scope, $element, $attrs) {
var ctrl = this;
ctrl.user = $scope.$parent.textFields.whatWeDo.title;
var x = ctrl.obj;
}
myApp.component('paragraphComponent', {
templateUrl: '/app/Views/paragraphCom.html',
bindings: {
obj : '='
},
controller: paragraphController
})
Please help, I need to wrap my head around component before end of today, I've been reading on this for the whole night yesterday and still don't quite grasp it. I don't even understand the benefit of component, when directive can do more from my understanding
Upvotes: 1
Views: 38
Reputation: 136184
Don't worry, its nothing new. AngularJS component API is just a wrapper around a directive API. Behind the scenes it create a directive when you use .component
API. These change has been introduced to make a migration of AngularJS to Angular(2+) version smoother. Also API readability will also looks similar as Angular is totally based on component
.
Coming back to your questions
controllerAs
pattern while defining a controller, all the binding value resides inside your $scope.controllerAlias
variable. Eventually if you see whats there in alias, you will see that this
(context) is exactly populated over there. There you shouldn't be using $scope
inside a controller, rather everthing will be resides inside you controller function this
, which is nothing but $ctrl
default controller alias. You had typo while using your component name. paragraph-Component
tag should be paragraph-component
<paragraph-component obj="paragraphToWrite"></paragraph-component>
Upvotes: 1