[英]Call directive controller methods from outside
我編寫了提供選項卡功能的指令,我使用的是AngularJS(v1)的最新版本。 在我的指令中,我有一個將api公開給子指令的控制器,作用域在所有指令中都是隔離的:
家長指令
scope: {},
controller: function($scope) {
$scope.values = [];
this.addValue = function(value) {
$scope.values.push(value);
}
}
子功能鏈接指令
scope: {},
transclude: true,
template: '<div ng-transclude></div>',
replace: true,
link: function(scope, element, attr, parentCtrl)
{
parentCtrl.addValues('test')
}
在子指令中,我有一個帶有自己控制器的自定義html: TestCtrl
function TestCtrl($scope){
var vm = this;
... other logic
}
實作
<parent>
<child>
<div ng-controller="TestCtrl as t">
<button ng-click="addValues('new_test')"></button>
</div>
</child>
</parent>
我需要在單擊我的按鈕時調用“ addValues”方法(內部指令控制器)。
如何組織代碼來做到這一點?
var module = angular.module('app', []); module.controller('root', function ($scope) { $scope.test = function () { console.log('i am clicked'); } }); module.component('child', { template: '<button type="button" data-ng-click="$ctrl.click()">Click me</button>', controller: myController, bindings: { onClick: '&' } }); function myController() { var ctrl = this; ctrl.click = function () { this.onClick(); } }
<html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script> </head> <body data-ng-app="app"> <div data-ng-controller="root"> <child data-on-click="test()"></child> </div> </body> </html>
這只是一個示例在這里您可以閱讀更多內容。 希望這可以幫助。
也許在這里閱讀有關angular的最佳實踐會很有用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.