angular js scope属性未定义

时间:2013-06-30 16:14:33

标签: angularjs angularjs-directive angularjs-scope

为什么$ scope.orderBy未定义? 不应该是“测试”吗?

http://jsfiddle.net/XB4QA/4/

var app = angular.module("Foo", []);

app.directive("two", function () {
return {
    scope: {
        orderBy: '@'
    },
    restrict: 'E',
    transclude: true,
    controller: function ($scope, $element, $attrs) {
        console.log($scope.orderBy); // is undefined, why?   
    },
    template: '<div></div>',
    replace: true
};
});

<div ng-app="Foo">
    <two order-by="test">test</two>
</div>

2 个答案:

答案 0 :(得分:1)

@绑定在指令范围内插入,此插值在指令链接阶段之后发生。这意味着虽然指令模板可以使用绑定,但它们在各种指令配置方法中将不可用。但是,=绑定可立即用于指令,因此如果您想立即访问,我建议使用这样的绑定。

如果test是您要访问的文字值,请在属性值周围添加单引号,例如:

<two order-by="'test'">

如果test是变量,则只保留HTML。无论哪种情况,都要更改绑定,如:

scope: {
    orderBy: '='  // = instead of @
}

答案 1 :(得分:0)

如果你想使用字符串插值(使用@似乎就是这种情况),你应该使用Ajay在当前接受的答案的评论中提到的$observe

或者,如果您的orderBy属性始终是文字字符串,则可以创建空隔离范围,不要尝试绑定orderBy。然后,您可以使用$attrs.orderBy来获取字符串值。

这很好用。

app.directive("two", function () {
  return {
    scope: {
      orderBy: '@'
    },
    restrict: 'E',
    transclude: true,
    controller: function ($scope, $element, $attrs) {
      $attrs.$observe('orderBy', function() {
        console.log($scope.orderBy);
      });
    },
    template: '<div></div>',
    replace: true
  };
});

这样做:

app.directive("two", function () {
  return {
    scope: {
    },
    restrict: 'E',
    transclude: true,
    controller: function ($scope, $element, $attrs) {
      console.log($attrs.orderBy);
    },
    template: '<div></div>',
    replace: true
  };
});