gpt4 book ai didi

javascript - $watch 检查 AngularJS 范围内定义的变量

转载 作者:行者123 更新时间:2023-11-27 23:27:49 25 4
gpt4 key购买 nike

我有以下指令来显示警报,所以我想在显示变量更改为星号时捕获运行超时,我该怎么做?

链接函数仅在第一次被调用,但所有变量显示、消息和类型均未定义

指令代码

 angular.module('pysFormWebApp')      
.directive('alertDirective',

function alertDirective ($timeout) {
return {
restrict : 'E',
scope : {
message : "=",
type : "=",
show : "=",
test : "="
},
controller : function ($scope) {

$scope.closeAlert = function () {
$scope.show = false;
$scope.type = "alert alert-dismissable alert-";
$scope.message = "";
};

$scope.getStrongMessage = function (type) {
var strongMessage = "";
if(type == "success"){
strongMessage = "\xC9xito ! ";
} else if(type == "warning"){
strongMessage = "Cuidado ! ";
return strongMessage;
}
},
link: function(scope, element, attrs) {
scope.$watch(scope.show,
function (newValue) {
console.log(newValue);
},true);
},
templateUrl : "views/utilities/alert.html"
};
});

html指令代码

<div ng-show="show">
<div class="alert alert-dismissable alert-{{type}}">
<button type="button" class="close" ng-click="closeAlert()">&times;</button>
<strong>{{getStrongMessage(type)}}</strong> {{ message | translate }}
</div>
</div>

Controller 示例

  $scope.info.alert = {
message: "EXPOTED-SUCCESS",
type: "success",
show : true
};

html代码

<alert-directive  message="info.alert.message" 
type="info.alert.type"
show="info.alert.show">
</alert-directive>

最佳答案

您在范围变量上设置监视时犯了错误。基本上 $watch 将第一个参数作为 string/function ,它在每个摘要周期上进行评估,第二个参数将是回调函数

//replaced `scope.show` by `'show'` 
scope.$watch('show', function (newValue) {
console.log(newValue);
},true);

关于javascript - $watch 检查 AngularJS 范围内定义的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34814882/

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