Angularjs directive

Angularjs directive

本文关键字:directive Angularjs      更新时间:2023-09-26

我想要一个类似于ng模型的属性指令。我只想额外地将一个输入字段值绑定到一个范围变量(只在一个方向上输入字段->范围变量)。所以我刚刚尝试了这个指令,但无论如何都无法调用该指令。

脚本:

.directive('passivemodel', function () {
  return {
    restrict: "A",
    scope: {
        passivemodel: '='
    },
    link: function (scope, element, attrs) {
        scope.$watch('passivemodel', function(newPassivemodel, oldPassivemodel) {
            console.log("passive model", newPassivemodel);
        });
    }
  };
})

html:

<input data-passivemodel="keyword">

编辑:

嗯。。根据vilo20的回答,我遇到了一个非常奇怪的行为。

虽然此代码运行良好:<input data-ng-model="keyword" data-passivemodel="keyword">

这个没有(注意passivemodel的值):CCD_ 2。当然,我已经在控制器中定义了变量。

控制器:

.controller('SearchController', function($scope, $routeParams, $search) {
        $scope.search = new $search();
        $scope.keyword = "";
        $scope.keyword2 = "";
})

伊迪丝2:这是一把小提琴http://jsfiddle.net/HB7LU/12107/

试试这个:

.directive('passivemodel', function () {
        return {
            restrict: "A",
            scope: {
               passivemodel: '='
            },
            link: function (scope, element, attrs) {
                console.log("passive model", scope.passivemodel);
                $scope.$watch('passivemodel', function(newPassivemodel, oldPassivemodel) {
                //put your logic when passivemodel changed
                });
            }
        };
    })

希望它能帮助

编辑:这是一个plunkerhttp://plnkr.co/edit/T039I02ai5rBbiTAHfzv?p=preview

使用范围属性:

.directive('passivemodel', function () {
        return {
            restrict: "A",
            scope: {
                "passivemodel": "="
            },
            link: function (scope, element, attrs) {
                console.log("access passivemodel: ", scope.passivemodel);
            }
        };
    })

最后就这么简单:

.directive('modelRed', [function(){
        return {
            require: 'ngModel',
            restrict: 'A',
            scope: {},
            link: function (scope, element, attrs, ngModel) {
                scope.$watch(function () {
                    return ngModel.$modelValue;
                }, function(newValue) {
                    scope.$parent[attrs.modelRed] = newValue;
                    //console.log(attrs.modelRed, newValue, scope);
                });
            }
        }
    }])

在html:中

<p><input type="text" data-ng-model="testInput" data-model-red="redInput">{{redInput}}</p>

当然,您必须在$scope对象中定义testInputredInput