Setting $ scope variables from a directive

This guy is in this directive: Dynamic template in attribute-based directive?

Anyway, this is what I'm trying to accomplish.

This <titlebar> directive can accept the edit-button attribute. If this exists, and when the button is clicked, I would like to set the $ scope variable in my controllers, which will switch the button visibility for deleting / editing the element.

For example, if I set $scope.currentlyEditting = true; in my directive, I bind this to the controller and then use ng-show to show / hide the controls. I just don't know how to get this data in my controller.

titleBar directive :

 robus.directive("titlebar", function() { return { restrict: "E", template: "<header class='bar-title' ng-class='{\"sub-view\": view}'>"+ "<a class='button' ng-click='goBack()' ng-show='back'><i class='icon-arrow-left'></i> Back</a>" + "<h1 class='title' ng-transclude>" + "<span class='sub-title' ng-show='view'>{{view}}</span></h1>" + "<a class='button' ng-click='showEdit()' ng-show='edit'>Edit</a>" + "</header>", scope: { view: '@view', edit: '@editButton', back: '@backButton' }, transclude: true, replace: true, link: function ($scope, $element, attrs, ctrl) { // $scope.$apply(); }, controller: function($scope, $element, $attrs, $location, $routeParams) { /* simple back button implementation */ $scope.goBack = function() { history.back(-1) } // $scope.showEdit = function() { // $scope.currentlyEditting = true; // } } } }); 
+4
source share
2 answers

You have several options for this.

Instead of creating an isolation $scope.$eval(attrs.editButton) you can use $scope.$eval(attrs.editButton) (or view or backButton ) to handle attributes from the directive. Then you can set the variables and call functions depending on which area you worked in.

If you want to continue using the isolation area, you can also pass a function using & , which can switch the editing mode.

This will be done like this:

 // In the directive template: '...<a href="" ng-click="toggleEdit()">Edit</a>...', scope: { ... toggleEdit: '&', ... } // In the HTML (or directive template) <titlebar ... toggle-edit="toggleEditMode()" ...>...</titlebar> // In the controller (ngController, not directive controller) $scope.toggleEditMode = function() { $scope.editMode = !$scope.editMode; } 

Finally, you can also use $scope.$parent Parent to access the parent scope from the isolation scope in the directive. I do not recommend this because it creates a tight connection between the directive and your controller, but it is an option.

+6
source

I assume you want to pass it back to the parent controller. In the scope attribute, you use the "@" binding, which is one way. You can use "=" to bind the two methods. I did Plunker to show this: http://plnkr.co/edit/HBPcsT?p=preview

Just in case you need to save it inside the directive, I also showed an example of this.

+1
source

Source: https://habr.com/ru/post/1488775/


All Articles