将文字属性值传递给angular js指令

时间:2014-01-30 08:08:07

标签: angularjs angularjs-directive

我在理解属性值在AngularJS指令中的工作方式时遇到了一些麻烦。无论我尝试什么,当我尝试在指令控制器中使用它们时,文字属性值都会显示为undefined

在我的HTML中说我引用了这样的指令:

<div ng-controller="MyCtrl">
    <my-directive reference-attr='referenceVal' literal-attr='literalVal'></my-directive>
</div>

referenceValliteralVal都在我的控制器中定义,如下所示:

var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
    $scope.referenceVal = 'This was passed by reference';
    $scope.literalVal = 'This was also passed by reference, but should have been literal';
}

我试着在我的指令中选择它们:

myApp.directive("myDirective", function () {

    return {
        restrict: "E",
        replace: true,
        scope: {
            referenceAttr: "=",
            literalAttr: "@"
        },
        template: '<div><p>Reference:{{referenceAttr}}</p><p>Literal:{{literalAttr}}</p></div>',
        controller: function ($scope) {
            alert("ref: " + $scope.referenceAttr + ", lit: " + $scope.literalAttr);
        }
    };
});

输出看起来很好:

Reference: This was passed by reference
Literal: literalVal

但警告信息是废话:

ref: This was passed by reference, lit: undefined

您可以使用this JSFiddle

自行试用

为什么literalAttr在指令范围内未定义?

1 个答案:

答案 0 :(得分:3)

这是Angular最早版本的问题,例如:小提琴中使用的1.0.1。最新版本表现出预期的行为。