gpt4 book ai didi

angularjs - 通过观察变量触发指令内的函数

转载 作者:行者123 更新时间:2023-12-02 02:59:16 25 4
gpt4 key购买 nike

假设我有以下指令:

angular.module("myModule", [])
.directive('myDirective', function ($timeout) {
return {
restrict: 'EA',
scope: {
value: '=',
valueIsValid: '='
},
link: function (scope, element, attrs) {

scope.returnValueIsValid = function() {
// return valueIsValid = true or false
};
}
}
});

调用方式如下:

 <div my-directive  value="value"  value-is-valid="valueIsValid"></div>

value 变量是指令的输入,如果 value 在 valueIsValid 变量中有效,则指令应返回该变量。有没有办法通过观察 valueIsValid 来触发验证功能?

最佳答案

我假设 valueIsValidvalue>0 时为真

var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',function($scope, $timeout) {

});

myApp.directive('myDirective', function ($timeout) {
return {
restrict: 'EA',
scope: {
value: '=',
valueIsValid: '='
},
link: function (scope, element, attrs) {
scope.$watch("value",function(a,b){
if(a && a != 0){
scope.valueIsValid =true;
}else{
scope.valueIsValid =false;
}
})
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<input type="number" value="0" ng-model="value"/>
<div my-directive value="value" value-is-valid="valueIsValid"></div>
value is valid:- {{valueIsValid}}
</div>

关于angularjs - 通过观察变量触发指令内的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47328401/

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