我有一个如下所示的自定义指令:
<div class="col-md-6">
{{templateMapping[colProp].SheetPointer}}
<select class="form-control"
ng-model="selectedColumn"
ng-change="changeMapping()"
ng-options="Col.SheetPointer for Col in optionList"></select>
</div>
注意ng-change
。
我的指令代码如下所示:
angular
.module('app.import')
.directive('mappingEdit', ['$rootScope', function ($rootScope) {
return {
restrict: "E",
templateUrl: "partials/templates/MappingEdit.html",
scope: {
templateMapping: "=", //parent object
colProp: "@", //name of property
optionList: "=",
colFilter: "=filter"
},
link: function (scope) {
scope.selectedColumn = {};
scope.changeMapping = function() {
// ng-change fired here!
scope.templateMapping[scope.colProp] = scope.selectedColumn;
// call "autoSave here, commitSave is in the Controller...
};
}
}
}]);
自定义指令的使用方式如下:
<mapping-edit
template-mapping="mapping"
col-prop="MappedColumn"
option-list="columnList"
filter="selectedSheet.SheetName" />
如您所见,我的指令 html 代码是 <select>
并有一个 ng-change
我想在 Controller 中调用一个名为 commitSave
的函数它看起来像下面这样:
$scope.commitSave = function () {
alert("on changed!")
}
如何使用 ng-change
从我的指令中调用此 Controller 函数?
最佳答案
您可以通过两种方式执行此操作。
您可以在范围定义中传递函数,例如:
scope: { templateMapping: "=", //parent object colProp: "@", //name of property optionList: "=", colFilter: "=filter" updateFn: "&" },
并在标记中:
<mapping-edit template-mapping="mapping" col-prop="MappedColumn" option-list="columnList" filter="selectedSheet.SheetName" updateFn="commitSave"/>
最后,在链接函数中:
scope.changeMapping = function() { // ng-change fired here! scope.templateMapping[scope.colProp] = scope.selectedColumn; scope.updateFn() };
使用事件:)
这是来自 Angular 文档的一个 plunker,正在演示。 http://plnkr.co/edit/UTPVE1qeTraJZcWRK1UO?p=info
关于javascript - AngularJS 指令与 Controller 对话以调用 onchange 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30197934/