angularjs-directive – AngularJS指令,从外面调用方法
我创建了一个方法,该方法应该从不是指令的一部分的其他元素调用.但是看起来这个方法是不暴露的.
一些例子翡翠代码澄清: //- a controller for the view itself div(ng-controller="someController") //- this is part of the view itself,not within the directive div(ng-repeat="element in elements") div(ng-click="methodFromDirective(element)") click element {{$index}} to trigger directive //- this is the directive div(some-directive) 我觉得someController在这里并不重要.它有方法,但不是methodFromDirective(element)方法. methodFromDirective(element)是仅在该指令中存在的方法. 如果我做出一个指令,并在创建时注意一些日志记录,我可以清楚地看到它的创建.但是,MethodFromDirective(element)方法不会公开,所以调用没有被正确的触发. methodFromDirective(element)本身只能用于指令模板中的元素. 一些coffeescript来显示该指令的定义(这里忽略缩进错误): 'use strict' define [],() -> someDirective = () -> restrict: 'A' scope: { show: '=' } transclude: false templateUrl: 'someTemplateHere.html' controller = ($scope) -> # exposing the method here $scope.methodFromDirective(element)-> $scope.theMethod element link = (scope,element,attr) -> # this is logged console.log "init someDirective" # triggering this method form outside fails scope.theMethod = (element)-> console.log "method triggered with element",JSON.stringify(element)
我找到了我的问题.
从the angularJS documentation on directives我正在研究转录选项,因为它表示:
我将transclude = false与控制器函数组合,因为它暴露了方法,再次从docs:
但是,我完全错过的是我在我的指示范围内列出了范围.来自文档:
因此,即使您使用transclude = false和控制器功能,如果使用隔离范围,您仍然无法公开方法!学过的知识! 在弄清楚出了什么问题的同时,我也做了一个小提琴,以便更好的理解:http://jsfiddle.net/qyBEr/1/ HTML <div ng-app="directiveScopeExample"> <div ng-controller="Ctrl1"> <p>see if we can trigger a method form the controller that exists in the directive.</p> <ul> <li><a href="#" ng-click="methodInController()">Method in Controller</a></li> <li><a href="#" ng-click="methodInDirective()">Method in Directive</a></li> </ul> <simple-directive/> </div> </div> JavaScript的 angular.module('directiveScopeExample',[]) .controller('Ctrl1',function Ctrl1($scope) { $scope.methodInController = function(){ alert('Method in controller triggered'); }; }) .directive('simpleDirective',function(){ return { restrict: 'E',transclude: false,controller: function($scope){ $scope.methodInDirective = function(){ // call a method that is defined on scope but only within the directive,this is exposed beause defined within the link function on the $scope $scope.showMessage('Method in directive triggered'); } } // this is the issue,creating a new scope prevents the controller to call the methods from the directive //,scope: { // title: '@' //},link: function(scope,attrs,tabsCtrl) { // view related code here scope.showMessage = function(message){ alert(message); } },//templateUrl: 'some-template-here.html' }; }) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |