365

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

我创建了这个 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);
    }
});

我错过了什么?

4

5 回答 5

578

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

更好的答案:

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>​​​​​​​​

您应该在这里注意到的一件事是,如果您想设置值字符串,您应该将它用引号引起来。(见第三个输入)

这是玩的小提琴: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.$ro​​otScope.Scope#$eval

在返回结果的当前范围内执行表达式。表达式中的任何异常都会传播(未捕获)。这在评估角度表达式时很有用。

于 2012-09-11T14:50:43.687 回答
83

对于需要在不使用隔离范围的指令中插入的属性值,例如,

<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.

于 2012-09-12T19:49:24.720 回答
4

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

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

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

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

工作小提琴

于 2014-04-05T16:00:36.050 回答
4

对于我正在寻找的相同解决方案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
于 2014-05-27T13:14:21.120 回答
2
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 加载后调用指令,所以你的更改不适用

于 2015-09-02T07:54:45.027 回答