【问题标题】:AngularJS: Exeucting function from controller in a directiveAngularJS:在指令中从控制器执行功能
【发布时间】:2014-11-29 19:42:52
【问题描述】:

我对 AngularJS 很陌生,我尝试执行以下操作:

使用自定义指令在元素上绑定滚动事件。 代码如下:

首先,我的控制器:

var officeUIApplication = angular.module('OfficeUI.Ribbon.Module', [])
.controller('OfficeUI', ['$scope', '$http', function($scope, $http) {
    var application = this;
    $scope.customAlert = function() {
        console.log('This ia scrolling demo.');
    }
}])

您会注意到,这里我有一个名为“CustomAlert”的函数。我不知道我为什么要把它绑定到 $scope,我只在下一个找到了这种信息。我可以删除范围还是有人可以解释我为什么它很重要?

然后我有指令:

.directive("ngcScroll", function() {
    return {
        restrict: 'A',
        link: function (scope, element, attributes) {
            scope.customAlert();
            element.on('DOMMouseScroll mousewheel', function (e) {
                console.log('Element is being executed.');
            });
        }
    }
});

console.log 已执行,所以这不是问题,它已执行,但在 scope.customAlert() 上我收到以下错误:

scope.customAlert is not a function.

我发现这样做如下:

scope.$apply('customAlert()');

但是,我收到 $apply is already in progress.

有人知道我应该如何实现这一目标吗?

亲切的问候,

【问题讨论】:

  • 我确实将其称为:
    • 执行 scope.customAlert();存在于控制器中?
    • 确实如此,但我似乎找到了解决方案。但是,我不知道我改变了什么:)
    • 你能发布你的解决方案吗?
    • 我会在代码完成后立即更新它,因为它现在非常混乱。

    标签: javascript html angularjs


    【解决方案1】:

    试试这个,

    1

    myApp.directive("ngcScroll", function($rootScope) {
        return {
            restrict: 'A',
            link: function (scope, element, attributes, ctrl) {  
                element.on('DOMMouseScroll mousewheel', function (e) {
                    scope.$apply(function () {
                        scope.customAlert();
                    })
                });
            }
        }
    });
    

    演示:http://jsfiddle.net/HB7LU/8642/

    2

    <div ng-controller="MyCtrl">   
        <div ngc-scroll custom-alert="customAlert()"> ConTEN </div>   
    </div>
    

    JS

    myApp.directive("ngcScroll", function() {
        return {
            restrict: 'A',
            scope: {
                customAlertFn: "&customAlert"
            },
            link: function (scope, element, attributes) {           
                element.on('DOMMouseScroll mousewheel', function (e) {
                    scope.customAlertFn();
                });
            }
        }
    
    });
    

    & 运算符允许您在任何指令的父范围内调用或评估表达式

    演示:http://jsfiddle.net/HB7LU/8640/

    3

    <div ngc-scroll> ConTEN </div> 
    

    JS

    var myApp = angular.module('myApp',[]);
    
    myApp.controller('MyCtrl', function ($scope, $rootScope) {
        $scope.customAlert = function() {
            console.log('This ia scrolling demo.');
        }
        
        $scope.$on('customAlert', $scope.customAlert);
    });
    
    myApp.directive("ngcScroll", function($rootScope) {
        return {
            restrict: 'A',
            link: function (scope, element, attributes) {  
                element.on('DOMMouseScroll mousewheel', function (e) {
                    scope.$emit('customAlert');
                });
            }
        }
    });
    

    【讨论】:

      【解决方案2】:

      好的,

      我找到了解决方案,实际上这很简单。我在错误的控制器中定义了模块,但现在它可以正常工作。

      这意味着代码看起来像:

      控制器:

      .controller('OfficeUI', ['$scope', '$http', function($scope, $http) {
          var application = this;
      
          // Load up the JSon data string containing the definition of the ribbon.
          $http.get('/OfficeUI/Resources/JSon/application.json').
              success(function (data) {
                  application.title = data.Title;
                  application.icons = data.Icons;
              }).
              error(function (data) {
                  // An error has occured while retrieving the data, so write it away in the logs.
                  console.log('An error occured while retrieving the data.');
              });
      }])
      

      指令:

      .directive("ngcScroll", function() {
          return {
              restrict: 'A',
              link: function (scope, element, attributes) {
                  element.on('DOMMouseScroll mousewheel', function (e) {
                      scope.$apply(attributes['ngcScroll'], 'demo');
                  });
              }
          }
      });
      

      HTML:

      <div ngc-scroll="enableTab(this)" class="ribbon officeui-borders-border-bottom-grey" ng-controller="OfficeUIRibbon as ribbon">
          <ul role="tabs" class="officeui-space-no-margin officeui-space-no-padding officeui-borders-border-bottom-grey">
              <li role="tab" ng-repeat="tab in ribbon.tabs" ng-class="{ application: $first, active: !$first && ribbon.isActive(tab.Id) }" class="officeui-display-inline-block" ng-click="$first || ribbon.setTab(tab.Id)">
                  <span>{{tab.Name}}</span>
                  <div id="{{tab.contentId}}" ng-class="{ 'officeui-display-block': !first && ribbon.isActive(tab.Id), 'officeui-display-hidden': !first && !ribbon.isActive(tab.Id)}" class="contents officeui-position-absolute">
                      {{tab.Contents}}
                  </div>
              </li>
          </ul>
      </div>
      

      【讨论】:

      • 干得好。我很高兴您发布了解决方案。我学到了一些新东西。我不能投票,因为我今天的票太多了。
      • “我将只从主控制器传递一个不带 = 符号的函数”怎么样? ?
      • @Alexander 对不起,我错了。我已经删除了那个问题。
      • @Complexity 这种情况会改变一切...... :)。无论如何感谢分享您的解决方案...
      【解决方案3】:

      从你的指令代码中这应该可以工作:

      link: function (scope, element, attributes) {
          scope.$parent.customAlert();
          element.on('DOMMouseScroll mousewheel', function (e) {
              console.log('Element is being executed.');
          });
      }
      

      通过以下方式访问父作用域上的任何方法和属性:

      scope.$parent
      

      这里需要注意的是,虽然这是访问父作用域方法的一种非常直接的方式,但它非常不灵活,因为它总是对父作用域上存在的内容做出假设。使用 Alexander 建议的隔离范围可以提供更大的灵活性。当您将指令放在不同的父范围内时,您可以通过 HTML 属性将要调用的实际父方法传递给指令。

      【讨论】:

        【解决方案4】:

        var myApp = angular.module('myApp',['ngRoute']);
        
        //myApp.directive('myDirective', function() {});
        //myApp.factory('myService', function() {});
        
        
        myApp.controller("MyCtrl",['$scope',function($scope){
            $scope.$on("receive",function(f,e){
                alert(e);
            });
        }]);
        myApp.directive("ngcScroll", function() {
            return {
                restrict: 'A',
                link: function (scope, element, attributes) {
                    element.on('DOMMouseScroll mousewheel', function (e) {
                       scope.$emit("receive","djfhdfdhfdhfgdhf");
                    });
                }
        }
        
        });
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
        <script src="https://code.angularjs.org/1.2.27/angular-route.js"></script>
        
        <div ng-app="myApp">
        <div ng-controller="MyCtrl">
            <div ngc-scroll>
                A root scope can be retrieved using the $rootScope key from the $injector. Child scopes are created using the $new() method. (Most scopes are created ...<br /><br /><br /><br /><br />  A root scope can be retrieved using the $rootScope key from the $injector. Child scopes are created using the $new() method. (Most scopes are created ...<br /><br /><br /><br /><br />  A root scope can be retrieved using the $rootScope key from the $injector. Child scopes are created using the $new() method. (Most scopes are created ...<br /><br /><br /><br /><br />  A root scope can be retrieved using the $rootScope key from the $injector. Child scopes are created using the $new() method. (Most scopes are created ...<br /><br /><br /><br /><br />  A root scope can be retrieved using the $rootScope key from the $injector. Child scopes are created using the $new() method. (Most scopes are created ...<br /><br /><br /><br /><br />  A root scope can be retrieved using the $rootScope key from the $injector. Child scopes are created using the $new() method. (Most scopes are created ...<br /><br /><br /><br /><br />  A root scope can be retrieved using the $rootScope key from the $injector. Child scopes are created using the $new() method. (Most scopes are created ...<br /><br /><br /><br /><br />  A root scope can be retrieved using the $rootScope key from the $injector. Child scopes are created using the $new() method. (Most scopes are created ...<br /><br /><br /><br /><br />  A root scope can be retrieved using the $rootScope key from the $injector. Child scopes are created using the $new() method. (Most scopes are created ...<br /><br /><br /><br /><br />  A root scope can be retrieved using the $rootScope key from the $injector. Child scopes are created using the $new() method. (Most scopes are created ...<br /><br /><br /><br /><br />  A root scope can be retrieved using the $rootScope key from the $injector. Child scopes are created using the $new() method. (Most scopes are created ...<br /><br /><br /><br /><br />  A root scope can be retrieved using the $rootScope key from the $injector. Child scopes are created using the $new() method. (Most scopes are created ...<br /><br /><br /><br /><br />  A root scope can be retrieved using the $rootScope key from the $injector. Child scopes are created using the $new() method. (Most scopes are created ...<br /><br /><br /><br /><br />  A root scope can be retrieved using the $rootScope key from the $injector. Child scopes are created using the $new() method. (Most scopes are created ...<br /><br /><br /><br /><br />  A root scope can be retrieved using the $rootScope key from the $injector. Child scopes are created using the $new() method. (Most scopes are created ...<br /><br /><br /><br /><br />  A root scope can be retrieved using the $rootScope key from the $injector. Child scopes are created using the $new() method. (Most scopes are created ...<br /><br /><br /><br /><br />  A root scope can be retrieved using the $rootScope key from the $injector. Child scopes are created using the $new() method. (Most scopes are created ...<br /><br /><br /><br /><br />  A root scope can be retrieved using the $rootScope key from the $injector. Child scopes are created using the $new() method. (Most scopes are created ...<br /><br /><br /><br /><br />  A root scope can be retrieved using the $rootScope key from the $injector. Child scopes are created using the $new() method. (Most scopes are created ...<br /><br /><br /><br /><br />  A root scope can be retrieved using the $rootScope key from the $injector. Child scopes are created using the $new() method. (Most scopes are created ...<br /><br /><br /><br /><br />  A root scope can be retrieved using the $rootScope key from the $injector. Child scopes are created using the $new() method. (Most scopes are created ...<br /><br /><br /><br /><br />  A root scope can be retrieved using the $rootScope key from the $injector. Child scopes are created using the $new() method. (Most scopes are created ...<br /><br /><br /><br /><br />  A root scope can be retrieved using the $rootScope key from the $injector. Child scopes are created using the $new() method. (Most scopes are created ...<br /><br /><br /><br /><br />  A root scope can be retrieved using the $rootScope key from the $injector. Child scopes are created using the $new() method. (Most scopes are created ...<br /><br /><br /><br /><br />
        
        
            </div>
        
        </div>
          
          </div>

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-02-15
          • 2014-10-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-04-29
          相关资源
          最近更新 更多