gpt4 book ai didi

javascript - 从 Angular Directive(指令)调用 Controller 函数

转载 作者:行者123 更新时间:2023-11-29 19:45:18 24 4
gpt4 key购买 nike

如何在 Controller 中定义的指令中调用 Angular 函数?

var app = angular.module('myApp', ['ngResource']);

app.directive('hello', function () {
return {
scope: {
myObj: '=hello'
},
template: '<button class="btn btn-primary" ng-click="dirFunction()">Click</button>',
link: function (scope) {
scope.dirFunction = function () {
scope.count++;
console.log('I am dirFunction');
};
var countChange = function (someVar) {
console.log('I am countChange');
// scope.changeCount(someVar); // call changeCount() defined in controller
};

// scope.$watch('myObj', hello);
scope.$watch('count', countChange);
}
}
});


function MyCtrl($scope) {
$scope.message = 'Can I do it?';
$scope.myObj = {data:'I need this data object',count:1};

$scope.changeCount = function(someVar) {
console.log("I am changeCount from controller,I have someVar in hand");
}

}

我需要在指令中调用注释的 scope.changeCount(someVar);

参见 HTML,

<div ng-app="myApp">
<div class="container" ng-controller="MyCtrl">
<div class="row">
{{message}}
<div hello="myObj"></div>
</div><!--/row-->
</div>
</div>

Fiddle here.

最佳答案

使用 & 在使用隔离作用域的指令内部调用父作用域上的 Controller 函数时:

HTML

<div hello="myObj" change-count="changeCount(someVar)"></div> 

指令

app.directive('hello', function () {
return {
scope: {
myObj: '=hello',
changeCount:"&changeCount"
},
template: '<button class="..." ng-click="dirFunction()">Click</button>',
link: function (scope) {
scope.dirFunction = function () {
scope.myObj.count++;
console.log('I am dirFunction '+scope.myObj.count);
};
var countChange = function (someVar) {
console.log('I am countChange '+someVar);
scope.changeCount({'someVar':someVar});
};
scope.$watch('myObj.count', function(newValue){
countChange(newValue)
});
}
}
});

Fiddle

关于javascript - 从 Angular Directive(指令)调用 Controller 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20144463/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com