ng-单击角度指令 - 从根范围传递函数
ng-click in angular directive - pass function from root scope
修复了这个问题,这是显示它工作的最后一个小提琴:
http://jsfiddle.net/mbaranski/tfLeexdc/
我有一个指令:
var StepFormDirective = function ($timeout, $sce, dataFactory, $rootScope) {
return {
replace: false,
restrict: 'AE',
scope: {
context: "=",
title: "="
},
template: '<h3>{{title}}</h3><form id="actionForm" class="step-form"></form><button ng-click="alert()" type="button">Save</button>',
link: function (scope, elem, attrs) {
}
}
}
如何让alert()
从控制器执行某些操作?
这是一个小提琴:http://jsfiddle.net/mbaranski/tfLeexdc/
Angular 可能会抽搐,所以我构建了一个全新的小提琴来演示完成这项工作所需的所有"胶合"部分。
首先,您没有将属性传递给指令,因此我进行了调整:
// You have to pass the function in as an attribute
<hello-directive list="osList" func="myFunc()"></hello-directive>
其次,您在模板中使用onclick
而不是ng-click
,这是问题的一部分,所以我进行了切换:
// You need to use "ng-click" instead of "onclick"
template: '<h3>{{list}}</h3><button ng-click="func()" type="button">Button</button>',
最后,您需要在指令范围内绑定函数,然后通过绑定名称调用它:
scope: {
list: "=",
// Bind the function as a function to the attribute from the directive
func: "&"
},
这是一个工作小提琴
所有这些粘在一起看起来像这样:
.HTML
<div ng-controller="MyCtrl">
Hello, {{name}}!
<hello-directive list="osList" func="myFunc()"></hello-directive>
</div>
爪哇语
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.name = 'Angular Directive';
$scope.osList = "Original value";
$scope.stuffFromController = {};
$scope.myFunc = function(){ alert("Function in controller");};
};
var HelloDirective = function() {
return {
scope: {
list: "=",
func: "&"
}, // use a new isolated scope
restrict: 'AE',
replace: false,
template: '<h3>{{list}}</h3><button ng-click="func()" type="button">Button</button>',
link: function(scope, elem, attrs) {
}
};
};
myApp.directive("helloDirective", HelloDirective);
如果要执行在其他地方定义的函数,请确保通过 scope
指令属性传入该函数。
在这里你可以做:
scope: {
context: '=',
title: '=',
alert='&' // '&' is for functions
}
在使用指令的位置,您将传递函数的"表达式"(不仅意味着函数,还意味着您希望在单击发生时发生函数的实际调用。
<step-form-directive alert="alert()" title=".." context=".."></step-form-directive>
相关文章:
- ES6是否引入了一种机制来生成块范围的函数语句(而不是表达式)
- 如何传递函数中的参数
- 如何在单击、Knockout时传递函数中的值
- D3选择html——传递函数时,索引从1开始,而不是从0开始
- 在谷歌地图的addListener事件中传递函数
- 如何在javascript中设置传递函数
- 什么's调用函数和传递函数的区别
- 在Angular Directive中传递函数作为参数不会;不起作用
- Skrollr:当滚动位置在最后一个关键帧之后时传递函数
- 在JS中传递函数作为参数,并访问接收函数's变量
- 如何在aspx页面中的转发器ItemDataBound中传递函数中的Control.ClientID
- setTimeout()/setInterval()赢得't执行**我正在传递函数对象,而不是执行函数
- WaveShaperNode的传递函数
- 将“this”范围传递给回调函数
- 在 .on('click') 事件处理程序中传递函数和函数参数
- 通过 x 标记访问器传递函数
- javascript:传递函数
- ES6类,传递函数作为参数来注册expressjs路由
- JavaScript:获取传递函数的参数
- ng-单击角度指令 - 从根范围传递函数