如何在我的情况下操纵子元素

时间:2014-09-23 18:19:09

标签: javascript html angularjs

我正在尝试检测文档点击页面并在div中操作dom。我有类似

的东西
angular.module('myApp').directive('documentClick', ['$document', function($document) {
    return function(scope, element, attrs) {
        element.bind('click', function(e){
            console.log('click')
        })
    }
}]);


<body ng-app="myApp" ng-controller="ctrl" document-click>
    <div ng-controller='insideCtrl'>
       <div id="test">
           <p>inside p</p>
       </div>
    </div>
</body>

我想在p&#39;内部改变在我点击任何地方的页面之后发送到其他内容我该怎么做呢?感谢。

1 个答案:

答案 0 :(得分:1)

您可以使用事件来解决问题。

控制器发出事件,您可以在指令中注入的唯一控制器是$rootController。所以,让我们这样做:

// in your directive
angular.module('...')
  .directive('documentClick', function ($document, $rootScope) {
    return function(scope, element, attrs) {
        element.bind('click', function(e){
        $rootScope.$broadcast('documentClicked');
      })
    }
  });

// in your controller
angular.module('...')
  .controller('WhateverCtrl', function ($scope) {

     $scope.$on('documentClicked', function () {
       // here it is !
     });

  });

请注意,我在控制器中使用了$scope,而不是$rootScope因为没有必要使用它,广告$broadcast被发送到所有子范围。 See here for more infos

相关问题