我正在尝试为用作属性的 Angular JS 指令引入一个变量。
让我们以petFilter
为例。
HTML:
<input type="text" name="catName" pet-filter='cat'>
<input type="text" name="dogName" pet-filter='dog'>
这样,如果我在两个输入中输入“Foxy”和“Brownie”,我就会退出:
Foxy is a cat!
Brownie is a dog!
到目前为止我所拥有的是:
JS:
.directive('petFilter', function(){
return {
restrict: 'A',
require : 'ngModel',
scope : true,
link: function($scope, elem, attrs, ctrl){
$scope.$watch(attrs.ngModel, function () {
var temp = ctrl.$viewValue;
var petType = ????;
outputFunction( temp + 'is a ' + petType + '!');
})
}
};
})
我只是不知道如何设置 petType
的值。
最佳答案
对于您的示例,您实际上不需要 $watch,它用于绑定(bind)到作用域上的变量。值“dog”和“cat”位于传入的属性中,在您的情况下,它看起来像:
{
petFilter: "cat"
}
或者如果您使用不同的属性,例如 ,它看起来像:
{
petType: "dog"
}
因此,要在指令中使用它,您只需从 attrs 对象访问它,如下所示:
.directive('petFilter', function(){
return {
restrict: 'A',
require : 'ngModel',
scope : true,
link: function($scope, elem, attrs, ctrl){
var petType = attrs.petFilter;
outputFunction( temp + 'is a ' + petType + '!');
}
};
})
编辑:如果您想根据 ng-model 指令监视作用域上的属性,那么您已经很接近了,您所要做的就是添加 $watch 回调的参数。对于此示例,假设您的输入如下所示:
<input ng-model="petName" petFilter="cat">
那么你的指令将如下所示:
.directive('petFilter', function(){
return {
restrict: 'A',
require : 'ngModel',
scope : true,
link: function($scope, elem, attrs){
/** The callback we pass in here is called every time the value of the
scope expression, which in this case is "petName", changes. **/
$scope.$watch(attrs.ngModel, function (newValue, oldValue) {
/** newValue will be equal to $scope.petName. **/
var temp = newValue;
var petType = attrs.petFilter;
outputFunction( temp + 'is a ' + petType + '!');
})
}
};
})
关于javascript - Angular JS 属性指令采用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21147109/