简体   繁体   English

AngularJS:在指令中从控制器执行功能

[英]AngularJS: Exeucting function from controller in a directive

I'm very new to AngularJS and I try to do the following: 我是AngularJS的新手,我尝试执行以下操作:

Bind an scroll event on an element by using a custom directive. 使用自定义指令将滚动事件绑定到元素上。 Here's the code: 这是代码:

First of all, my controller: 首先,我的控制器:

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.');
    }
}])

You'll notice, that here I have function called 'CustomAlert'. 您会注意到,这里有个名为“ CustomAlert”的函数。 I don't know why I'm binding it to $scope, I've only found this kind of information on the next. 我不知道为什么将它绑定到$ scope,我仅在下一个发现了这种信息。 Can I remove the scope or can someone explain my why it's important? 我可以删除范围吗?有人可以解释为什么它很重要吗?

Then I have the directive: 然后我有了指令:

.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.');
            });
        }
    }
});

The console.log is executed, so that's not a problem, it's executed, but on the scope.customAlert() I receive the following error: console.log已执行,所以这不是问题,它已执行,但是在scope.customAlert()上,我收到以下错误:

scope.customAlert is not a function.

I've found to do it like follow: 我发现这样做的方法如下:

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

However, then I receive $apply is already in progress. 但是,然后我收到$ apply已经在进行中。

Anyone has an idea how I should achieve this? 有人知道我应该如何实现吗?

Kind regards, 亲切的问候,

Try this, 尝试这个,

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();
                })
            });
        }
    }
});

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

2 2

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

JS JS

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

});

& operator allows you to invoke or evaluate an expression on the parent scope of whatever the directive 运算符允许您在任何指令的父范围内调用或求值表达式

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

3 3

<div ngc-scroll> ConTEN </div> 

JS 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');
            });
        }
    }
});

Ok, 好,

I've found the solution, which was quite simple in fact. 我找到了解决方案,实际上很简单。 I had defined the module in a wrong controller, but right now it's working without an issue. 我在错误的控制器中定义了模块,但是现在它可以正常工作了。

This means the code looks like: 这意味着代码如下所示:

Controller: 控制器:

.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: 指示:

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

HTML: 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>

From inside your directive code this should work: 从您的指令代码内部,这应该起作用:

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

Access any methods and properties on the parent scope via: 通过以下方式访问父作用域上的任何方法和属性:

scope.$parent

The caveat here is while this is a pretty direct way to access a parent scope's method, it's pretty inflexible as it will always be making assumptions about what exists on the parent scope. 需要说明的是,虽然这是访问父范围方法的一种非常直接的方法,但由于总是将对父范围中存在的内容进行假设,因此它很不灵活。 Using an isolate scope as suggested by Alexander gives much greater flexibility. 使用亚历山大建议的隔离范围可提供更大的灵活性。 When you place your directive inside different parent scopes you can pass the actual parent method you want to call into the directive via the HTML attributes. 将指令放在不同的父范围内时,可以通过HTML属性将要调用的实际父方法传递给指令。

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM