如何从另一个指令切换隔离范围的变量

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

我多次使用同一个指令,该指令有编辑和预览两种模式。

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

当我在一个元素上切换到编辑模式时,如果另一个元素已经处于编辑模式,它将返回预览模式。 怎么做到的?

您可以使用 $broadcast 告诉所有其他范围您将进入编辑模式。

这是一个有效的 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();
    });
 },