Reputation: 239
I am completing a code academy challenge on directives and would like to know how I could write this function that is in my directive but in my controller instead. The directive uses element. How can I use element in my controller? I understand angular is against doing any dom manipulation in controllers and to rely on directives for that instead. Why is that?
This is the HTML where the directive is being defined:
<div class="main" ng-controller="MainController">
<div class="container">
<div class="card" ng-repeat="app in apps">
<app-info info="app"></app-info>
<install-app></install-app>
</div>
</div>
</div>
This is the code in the directive, which I am trying to get to work alone in the controller instead. Again I know this is not how you do things in angularjs, but I am just looking for practice.
app.directive('installApp', function() {
return {
restrict: 'E',
scope: {},
templateUrl: 'js/directives/installApp.html',
link: function(scope, element, attrs) {
scope.buttonText = "Install",
scope.installed = false,
scope.download = function() {
element.toggleClass('btn-active')
if(scope.installed) {
scope.buttonText = "Install";
scope.installed = false;
} else {
scope.buttonText = "Uninstall";
scope.installed = true;
}
}
}
};
});
I've tried adding this in my controller:
$scope.buttonText = "Install",
$scope.installed = false,
$scope.download = function ($element){
if($scope.installed) {
$scope.buttonText = "Install";
$scope.installed = false;
} else {
$scope.buttonText = "Uninstall";
$scope.installed = true;
}
};
But when I click "Install" it changed all the buttons to "Uninstall" instead of the single one that was clicked.
Upvotes: 0
Views: 58
Reputation: 399
If you just want to toggle the class on Button element based on scope.installed
value is true or false you can use ngClass directive
ng-class="{'ClassName':expressionValue}"
Upvotes: 1