angularjs - 使用隔离范围时从指令调用控制器的功能?
问题描述
我想调用Controller
from的一个函数Directive
,它是为了验证。但是当我使用隔离范围时,我对如何从指令中调用它有点困惑。这是指令的代码:-
App.directive('test',function(){
return{
require: "ngModel",
scope:{
a:"=",
b:"=",
c:'=',
d:'='
},
link: function(scope, element, attributes,modelVal )
{
modelVal.$validators.test= function(val)
{
return false;
//isolated scope values will make if condition true or false.
if(scope.a=="true"){
//I need to call a function of controller here. But how can
//i call that function from directive? this is my problem
}
}
scope.$watch("a", function()
{
modelVal.$validate();
});
}//end of link function;
}//end of return;
});//end of directive;
Function
在我的controller
,我想我不需要写controller code
。在我的 html 中,我将此指令称为:
<test a="1" b="2" c="3" d="4" ng-model="abc"></test>
我需要做哪些更改directive
才能调用controller function
which is $scope.testFunction()
?
解决方案
var module = angular.module('myModule', []);
module.controller('TestController', function($scope){
$scope.text = 'test';
// Will be invoked from 'test' directive
$scope.alertMe = function(text){
alert(text);
};
});
module.directive('test', function(){
return {
restrict: 'E',
template: '<input ng-model="text" ng-change="onChange(text)" />',
scope: {
text: '='
},
link: function(scope, elem, attr){
scope.onChange = function(text){
// Invoking parent controller function
scope.$parent.alertMe(text);
}
}
}
})
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myModule" ng-controller="TestController">
<test text="text"></test>
</div>
</body>
</html>
推荐阅读
- python - AWS Glue 不接受额外的 python 库
- c++ - 在挂钩函数 agument 上调用方法
- vba - 通过关闭提醒来触发 Outlook 定期电子邮件
- kivy - 如何在 .kv 文件中换行?
- google-app-engine - 不能通过 IAP 将 SSH 隧道连接到 App Engine 实例吗?
- unit-testing - > 未能应用插件“com.android.library”。> 无法添加任务“unitTestCoverage”,因为具有该名称的任务已存在
- python - 如果设置返回类型,Python 中的 VS Code 会更改代码的文本颜色
- refactoring - 通过示例重构 - 需要参考
- java - 如何在 Java 8 中最好地使用有序 Map
- vmware - 通过 API 删除 VMWare 模板