javascript - Angular JS 属性指令采用变量

标签 javascript angularjs angularjs-directive

我正在尝试为用作属性的 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/

相关文章:

javascript - 以唯一id作为引用删除firebase上的数据

javascript - 单击事件后,JavaScript 可以更改客户端页面中的 CSS 类吗?

javascript - 如何使用 angularjs 或 javascript 清除浏览器缓存?

javascript - 使用动态模板对 Angular Directive(指令)进行单元测试

javascript - 我可以在 angularjs 指令中使用 JQuery 插件吗?

javascript - 使用 console.log() 检测 HTML Canvas 中的形状、图像和鼠标溢出; (普通 JavaScript)

javascript - Google Maps JavaScript API V3 - Geocoder API 不返回地名

php - Angular - 存储复选框值并显示它们

Javascript 在评估所有参数之前返回结果?

javascript - AngularJS $apply 不工作