来自同一范围的Access指令

时间:2015-03-13 08:57:09

标签: angularjs angularjs-directive angularjs-scope

我创建了一个定义了方法的自定义指令:

app.directive('modal', function() {
  return {
    restrict: 'E',
    template: '<div class="modal" ng-show="visible">modal box</div>',
    scope: {
      ngModel: '='
    },
    link: function(scope, element, attrs) {
      scope.visible = false;
      scope.show = function () {
        this.visible = true;
      };
      scope.close = function () {
        this.visible = false;
      };
    }
  };
});

我正在使用它:

<button ng-click="modal.show()">Show modal</button>
<modal></modal>

但是我无法在同一范围内访问此modal指令。

我尝试使用已定义的id属性,例如:

<button ng-click="myModal.show()">Show modal</button>
<modal id="myModal"></modal>

甚至可以这种方式访问​​指令范围吗?

或者更好的方法是使用$rootScope或广播事件?

我不想在控制器中定义这个指令 - 控制器不应该知道它的存在。

4 个答案:

答案 0 :(得分:1)

您在架构中发现了问题。确实存在变通方法,但它们只会使问题变得更加复杂。

如果您寻找稳定的解决方案,请查看Angular Bootstrap$modal的代码。您将看到他们将$modal作为服务。

原因是(例如)以下内容:

  1. 可以从任何范围开始和关闭
  2. 模态的模板与其他代码分开。

答案 1 :(得分:0)

父控制器可以访问其子指令的范围。

Here我创造了一个小例子来说明我在说什么。除非你的指令中有scope属性,否则它将使用其父级的范围。

答案 2 :(得分:0)

我会参加活动:

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.showModal = function(){
        $scope.$parent.$broadcast("show-modal");
    };

    $scope.hideModal = function(){
        $scope.$parent.$broadcast("hide-modal");
    };
}

myApp.directive('modal', function() {
  return {
    restrict: 'E',
    template: '<div class="modal" ng-show="visible">modal box</div>',
    link: function(scope, element, attrs) {
      scope.visible = false;
      scope.$on('show-modal', function(){
          scope.visible = true;
      });

      scope.$on('hide-modal', function(){
          scope.visible = false;
      });
    }
  };
})

基本上:从控制器广播一个事件(显示&#39;或者隐藏&#39;),在指令中捕获它并执行你的逻辑。

你的html模板:

<div ng-controller="MyCtrl" ng-app="myApp">
  <button ng-click="showModal()">Show modal</button>
    <br/>
    <button ng-click="hideModal()">Hide modal</button>
  <modal></modal>
</div>

答案 3 :(得分:0)

您的观点可能如下所示:

<button ng-click="showModal()">Show modal</button>
<modal></modal>

除了隔离范围之外,您可以将方法放在$ rootScope中。只有模板使用它隔离的范围和在其上定义的变量。

这是一个修改过的例子:

app.directive('modal', function ($rootScope) {
    return {
        restrict: 'E',
        template: '<div ng-show="visible">modal box</div>',
        scope: {},
        link: function (scope, element, attrs) {
            scope.visible = false;
            $rootScope.showModal = function () {
                console.log("showModal");
                scope.visible = true;
            };
            $rootScope.closeModal = function () {
                console.log("closeModal");
                scope.visible = false;
            };
        }
    };
});