我希望我的指令支持ng-change事件,但是我没有定义在触发ng-change时要调用的特定函数,我想启用ng-change来使用单个或多个参数来执行任何类型的函数并执行它。我可以想到两种方式,但不知道哪种方式正确或哪种方法有效。它是这样的:
方法1:
HTML:
<currency-input width="200px" id="iextz" ng-model="currency1" ng-change="someFunction(argument1,argument2,.....)" currency="$" decimals="2"></currency-input>
JS:
numericApp.directive('currencyInput',........
...................................
return {
restrict: 'E',
scope:{
ngModel : "=",
id : "@"
},
link: function($scope, $elm, $attrs) {
........................................
*//some logic to execute the function passed to ng-change*
executeNgChangeFucntion(){
...........
...........
};
}]);
方法2
HTML:
<currency-input width="200px" id="iextz" ng-model="currency1" ng-change="change(someFunctionWithArguments)" currency="$" decimals="2"></currency-input>
JS:
numericApp.directive('currencyInput',........
...................................
return {
restrict: 'E',
scope:{
ngModel : "=",
id : "@"
},
link: function($scope, $elm, $attrs) {
........................................
//ng-change handler
$scope.change = function(someFunctionWithArguments){
//execute someFuncitonWithArguments
..........................
};
}]);
我对AngularJS的高级概念没有太多经验,所以无论我能想到什么,我都把它放在这里。如果有人可以提供一些意见,这将是一个很大的帮助。提前谢谢!
实际上我正在构建一个数字字段组件,它会根据设置的货币,设置十进制数字等来获取数字和格式,这种东西,无论如何重要的部分是它的供其他人使用(让我们说客户)。人们可以在他们的应用程序中使用此组件,他们需要处理通过ng-change进入字段的任何输入。他们有自己的事件处理程序。它可能是任何东西。因此,我需要提供一种方法,以便它们可以传递其中一个函数,以便在输入发生变化时执行(如n-change所发生的情况)。例如:
<decimal-input ng-model="employees.calculatedChangeAmounts[job.id][jobChangeReasonCodes[$index]].changeAmount" decimals="2" ng-change="recalculate.salaryAmount($index, job)"></decimal-input>
我希望这有助于消除任何疑虑。现在请帮助解决我的问题,谢谢!
答案 0 :(得分:2)
如果指令的唯一目的是格式化输入,那么最好使用现有的掩码输入指令之一。例如:https://github.com/angular-ui/ui-mask。
如果您确定需要创建新指令,则可能需要使用NgModelController来实现它。这是在指令中实现对双向绑定和验证的完全支持的标准方法。除自定义绑定外,ng-change
还可以直接与ng-model
一起接收更改通知。
指令的用户将使用ng-model
绑定到其范围内的模型,然后使用ng-change
处理其模型的更改值。例如:
<currency-input ng-model="item.currencyValue" ng-change="process(item.currencyValue)">
</currency-input>
(请记住ng-model
绑定中的always have a dot。
答案 1 :(得分:0)
如果输入了该指令,那么您可以考虑这个(或者通过在控制器中定义someFunction(arg...)
来实现您的第一种方法)。
numericApp.directive('currencyInput',........
...................................
return {
restrict: 'E',
scope:{
ngModel : "=",
id : "@"
},
link: function($scope, $elm, $attrs)
{
$elm.bind("change",function(evt){
alert("Value changed");
});
}]);
答案 2 :(得分:0)
我不确定我是否理解第一种方法,但第二种方法似乎与ng-changed&#34;应该如何&#34;使用。
我的HTML
<p>My phone is {{phoneNumber}} !</p>
<p>Increment the phone number below:</p>
<input type="checkbox" ng-model="checkBoxData" ng-change="changeNumber(myShitVar)" />
我的控制器
app.controller('MainCtrl', ['$scope', function($scope) {
$scope.phoneNumber = 23323123;
$scope.changeNumber = function(myShitVar) {
if (!myShitVar) {
$scope.phoneNumber++;
}
};
如果要向函数添加可变数量的参数,只需传递它们即可。您可以向函数传递多少个参数,如果未定义某些值,则它们将作为未定义传递。