Angular 指令未观看
Angular directive not watching
我正在使用 AngularJS 中的指令,我正在尝试检查我的字段是否为 $dirty,如果是,我想记录一条消息,当它发生变化时,我想显示另一条消息消息(这句话稍后会被替换为更复杂的内容)。
我想在所有输入中重复使用我的指令,但我不能。提前致谢。
<input ng-edited ng-model="stakeholder.nombre" name="nombre" type="text">
我的指令是这样的:
MetronicApp.directive('ngEdited', function () {
return {
restrict: 'A',
require: ['^form', 'ngModel'],
link: function (scope, elem, attrs, req) {
scope.elemDirty = req[1].$dirty;
scope.elemName = req[1].$name;
var doFunction = function () {
if (scope.elemDirty) {
console.log("true");
} else {
console.log("false");
}
};
scope.$watch(scope.elemName, doFunction, true);
}
};
});
基于this answer,为什么不试试
link: function (scope, elem, attrs, ngModel) {
var doFunction = function (isDirty) {
if (isDirty) {
console.log("true");
} else {
console.log("false");
}
};
scope.$watch(function(){return ngModel[1].$dirty;},doFunction);
}
编辑
我注意到在您的问题中您试图观察元素名称的变化。我不确定您将如何更改该属性,但如果您是,请使用 attrs.$observe
attrs.$observe('name', doFunction);
如果您使用的是参数(而不是字符串),则需要从函数中return它:
scope.$watch(function () {
return scope.elemName;
}, doFunction, true);
我正在使用 AngularJS 中的指令,我正在尝试检查我的字段是否为 $dirty,如果是,我想记录一条消息,当它发生变化时,我想显示另一条消息消息(这句话稍后会被替换为更复杂的内容)。
我想在所有输入中重复使用我的指令,但我不能。提前致谢。
<input ng-edited ng-model="stakeholder.nombre" name="nombre" type="text">
我的指令是这样的:
MetronicApp.directive('ngEdited', function () {
return {
restrict: 'A',
require: ['^form', 'ngModel'],
link: function (scope, elem, attrs, req) {
scope.elemDirty = req[1].$dirty;
scope.elemName = req[1].$name;
var doFunction = function () {
if (scope.elemDirty) {
console.log("true");
} else {
console.log("false");
}
};
scope.$watch(scope.elemName, doFunction, true);
}
};
});
基于this answer,为什么不试试
link: function (scope, elem, attrs, ngModel) {
var doFunction = function (isDirty) {
if (isDirty) {
console.log("true");
} else {
console.log("false");
}
};
scope.$watch(function(){return ngModel[1].$dirty;},doFunction);
}
编辑
我注意到在您的问题中您试图观察元素名称的变化。我不确定您将如何更改该属性,但如果您是,请使用 attrs.$observe
attrs.$observe('name', doFunction);
如果您使用的是参数(而不是字符串),则需要从函数中return它:
scope.$watch(function () {
return scope.elemName;
}, doFunction, true);