CheapD AKA Ju
CheapD AKA Ju

Reputation: 721

How to toggle a variable of an isolate scope from another directive

I use the same directive several time, the directive has 2 modes edit and preview.

function () {
    return {
        restrict: "E",
        scope : {
            model : '='
        },
        [...]
        controller : function($scope, $element){
            $scope.switchToEdit = function(){
                $scope.isEditMode = true;
            }
            $scope.switchToPreview = function(){
                $scope.isEditMode = false;
            }
         }
     }}

When I switch to edit mode on an element, if another is already in edit mode it shall get back on preview mode. How do it ?

Upvotes: 0

Views: 77

Answers (1)

Simon Staton
Simon Staton

Reputation: 4505

You can use a $broadcast to tell all other scopes that you are going into edit mode.

Here is a working fiddle: http://jsfiddle.net/gvuxbo7m/

controller : function($scope, $element, $rootScope){
    $scope.isEditMode = false;
    $scope.switchToEdit = function(){
        $scope.isEditMode = true;
        $rootScope.$broadcast('switchToEdit', $element);
    }
    $scope.switchToPreview = function(){
        $scope.isEditMode = false;
    }
    $rootScope.$on('switchToEdit', function(event, $el){
        if($el !== $element) $scope.switchToPreview();
    });
 },

Upvotes: 1

Related Questions