Javascript $watch检查范围AngularJS中定义的变量
我有下面的指令来显示警报,所以我想捕获当显示变量更改为star运行超时时,我如何才能做到这一点 link函数仅在第一次调用,但所有变量show、message和type都未定义 指令码Javascript $watch检查范围AngularJS中定义的变量,javascript,angularjs,angularjs-directive,angularjs-watch,Javascript,Angularjs,Angularjs Directive,Angularjs Watch,我有下面的指令来显示警报,所以我想捕获当显示变量更改为star运行超时时,我如何才能做到这一点 link函数仅在第一次调用,但所有变量show、message和type都未定义 指令码 angular.module('pysFormWebApp') .directive('alertDirective', function alertDirective ($timeout) { return { restrict : 'E',
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"
};
});
<div ng-show="show">
<div class="alert alert-dismissable alert-{{type}}">
<button type="button" class="close" ng-click="closeAlert()">×</button>
<strong>{{getStrongMessage(type)}}</strong> {{ message | translate }}
</div>
</div>
html指令代码
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"
};
});
<div ng-show="show">
<div class="alert alert-dismissable alert-{{type}}">
<button type="button" class="close" ng-click="closeAlert()">×</button>
<strong>{{getStrongMessage(type)}}</strong> {{ message | translate }}
</div>
</div>
html代码
<alert-directive message="info.alert.message"
type="info.alert.type"
show="info.alert.show">
</alert-directive>
在scope变量上设置watch时出错。基本上,
$watch
将第一个参数作为字符串
/函数
,在每个摘要循环中对其求值&第二个参数将是回调函数
//replaced `scope.show` by `'show'`
scope.$watch('show', function (newValue) {
console.log(newValue);
},true);
您的手表代码有误,应该是
范围。$watch('show'
在您的指令内感谢@PankajParkar我在这个错误中花费了这么多时间。您是对的,这是一个错误,我认为这对以后的参考更好