如何在自定义指令中获取计算的属性

How to get evaluated attributes inside a custom directive

本文关键字:获取 计算 属性 指令 自定义      更新时间:2023-09-26

我正在尝试从我的自定义指令中获取评估的属性,但我找不到正确的方法。

我创建了这个jsFiddle来详细说明。

<div ng-controller="MyCtrl">
    <input my-directive value="123">
    <input my-directive value="{{1+1}}">
</div>
myApp.directive('myDirective', function () {
    return function (scope, element, attr) {
        element.val("value = "+attr.value);
    }
});

我错过了什么?

注意:当我找到更好的解决方案时,我会更新这个答案。我也会保留旧的答案以备将来参考,只要它们保持相关。最新和最好的答案是第一位的。

更好的答案:

angularjs 中的指令非常强大,但需要时间来理解它们背后的进程。

在创建指令时,angularjs 允许您创建一个隔离的作用域,其中包含与父作用域的一些绑定。这些绑定由您在 DOM 中附加元素的属性以及您在指令定义对象中定义范围属性的方式指定。

您可以在作用域中定义 3 种类型的绑定选项,并将其编写为前缀相关属性。

angular.module("myApp", []).directive("myDirective", function () {
    return {
        restrict: "A",
        scope: {
            text: "@myText",
            twoWayBind: "=myTwoWayBind",
            oneWayBind: "&myOneWayBind"
        }
    };
}).controller("myController", function ($scope) {
    $scope.foo = {name: "Umur"};
    $scope.bar = "qwe";
});

.HTML

<div ng-controller="myController">
    <div my-directive my-text="hello {{ bar }}" my-two-way-bind="foo" my-one-way-bind="bar">
    </div>
</div>

在这种情况下,在指令范围内(无论是在链接函数还是控制器中(,我们可以像这样访问这些属性:

/* Directive scope */
in: $scope.text
out: "hello qwe"
// this would automatically update the changes of value in digest
// this is always string as dom attributes values are always strings
in: $scope.twoWayBind
out: {name:"Umur"}
// this would automatically update the changes of value in digest
// changes in this will be reflected in parent scope
// in directive's scope
in: $scope.twoWayBind.name = "John"
//in parent scope
in: $scope.foo.name
out: "John"

in: $scope.oneWayBind() // notice the function call, this binding is read only
out: "qwe"
// any changes here will not reflect in parent, as this only a getter .

"还行"答案:

由于这个答案被接受,但有一些问题,我将把它更新到一个更好的答案。显然,$parse 是一种不存在于当前范围属性中的服务,这意味着它只采用角度表达式而无法到达范围。 {{}}表达式是在 angularjs 启动时编译的,这意味着当我们尝试在指令postlink方法中访问它们时,它们已经被编译了。({{1+1}}已经在指令中2(。

这是您想要使用的方式:

var myApp = angular.module('myApp',[]);
myApp.directive('myDirective', function ($parse) {
    return function (scope, element, attr) {
        element.val("value=" + $parse(attr.myDirective)(scope));
    };
});
function MyCtrl($scope) {
    $scope.aaa = 3432;
}​

.

<div ng-controller="MyCtrl">
    <input my-directive="123">
    <input my-directive="1+1">
    <input my-directive="'1+1'">
    <input my-directive="aaa">
</div>​​​​​​​​

这里你应该注意的一件事是,如果你想设置值字符串,你应该用引号括起来。(请参阅第 3 条输入(

这是要玩的小提琴:http://jsfiddle.net/neuTA/6/

旧答案:

不会为像我这样可能被误导的人删除它,请注意,使用 $eval 是正确的方法,但$parse有不同的行为,你可能不需要使用它在大多数情况下。

做到这一点的方法再次是 使用scope.$eval .它不仅可以编译角度表达式,还可以访问当前范围的属性。

var myApp = angular.module('myApp',[]);
myApp.directive('myDirective', function () {
    return function (scope, element, attr) {
        element.val("value = "+ scope.$eval(attr.value));
    }
});
function MyCtrl($scope) {
   
}​

你缺少的是$eval.

http://docs.angularjs.org/api/ng.$rootScope.Scope#$eval

在返回结果的当前作用域上执行表达式。表达式中的任何异常都将传播(未捕获(。这在计算角度表达式时很有用。

对于需要在不使用隔离作用域的指令中进行插值的属性值,例如,

<input my-directive value="{{1+1}}">

使用属性的方法$observe

myApp.directive('myDirective', function () {
  return function (scope, element, attr) {
    attr.$observe('value', function(actual_value) {
      element.val("value = "+ actual_value);
    })
 }
});

从指令页面,

观察插值属性:使用 $observe 观察包含插值的属性的值变化(例如 src="{{bar}}" (。这不仅非常有效,而且也是轻松获取实际值的唯一方法,因为在链接阶段尚未评估插值,因此此时该值设置为 undefined

如果属性值只是一个常量,例如,

<input my-directive value="123">

如果值是数字或布尔值,并且需要正确的类型,则可以使用 $eval:

return function (scope, element, attr) {
   var number = scope.$eval(attr.value);
   console.log(number, number + 1);
});

如果属性值是字符串常量,或者您希望该值在指令中为字符串类型,则可以直接访问它:

return function (scope, element, attr) {
   var str = attr.value;
   console.log(str, str + " more");
});

但是,在您的情况下,由于您希望支持内插值和常量,请使用 $observe

这里的其他答案非常正确,也很有价值。但有时你只是想要简单:在指令实例化时获取一个普通的旧解析值,不需要更新,也不会弄乱隔离范围。例如,将声明性有效负载作为数组或哈希对象以以下形式提供给指令会很方便:

my-directive-name="['string1', 'string2']"

在这种情况下,您可以切入正题,只需使用一个漂亮的基本angular.$eval(attr.attrName)

element.val("value = "+angular.$eval(attr.value));

工作小提琴。

对于相同的解决方案,我正在寻找Angularjs directive with ng-Model.
下面是解决问题的代码。

    myApp.directive('zipcodeformatter', function () {
    return {
        restrict: 'A', // only activate on element attribute
        require: '?ngModel', // get a hold of NgModelController
        link: function (scope, element, attrs, ngModel) {
            scope.$watch(attrs.ngModel, function (v) {
                if (v) {
                    console.log('value changed, new value is: ' + v + ' ' + v.length);
                    if (v.length > 5) {
                        var newzip = v.replace("-", '');
                        var str = newzip.substring(0, 5) + '-' + newzip.substring(5, newzip.length);
                        element.val(str);
                    } else {
                        element.val(v);
                    }
                }
            });
        }
    };
});


HTML DOM

<input maxlength="10" zipcodeformatter onkeypress="return isNumberKey(event)" placeholder="Zipcode" type="text" ng-readonly="!checked" name="zipcode" id="postal_code" class="form-control input-sm" ng-model="patient.shippingZipcode" required ng-required="true">


我的结果是:

92108-2223
var myApp = angular.module('myApp',[]);
myApp .directive('myDirective', function ($timeout) {
    return function (scope, element, attr) {
        $timeout(function(){
            element.val("value = "+attr.value);
        });
    }
});
function MyCtrl($scope) {
}

使用 $timeout因为指令在 dom 加载后调用,因此您的更改不适用