Angular:覆盖' @'链接或控制器中的隔离范围中的属性

时间:2015-02-19 15:27:12

标签: javascript angularjs

我有这样的指示:

  .directive('myPane', function() {
    return {
      restrict: 'E',
      transclude: true,
      scope: {
        title: '@'
      },
      controller: function($scope, $timeout) {
        $scope.title = "Foo";
      },
      templateUrl: 'my-pane.html'
    };
  });

我的HTML看起来像这样:

  <my-pane title="Hello">
    <p>Lorem ipsum dolor sit amet</p>
  </my-pane>

my-pane.html

<h4>{{title}}</h4>
<div class="tab-pane" ng-transclude>
</div>

现在,出于某种原因,尝试覆盖title属性不起作用。

我的问题是,为什么不呢?

到目前为止我发现了:

  • link函数
  • 中的行为相同
  • attrs.title = "Foo"函数中使用link的行为符合我的要求
  • 使用$timeout(function(){ $scope.title = "Foo"; })这样的行为就像我希望的那样

相关的Plunkr:http://plnkr.co/edit/SxbGj4BZlcSX1BfkSHbq?p=preview

1 个答案:

答案 0 :(得分:1)

您在指令中使用了@,但这只是单向数据绑定。您应该使用'=',即双向数据绑定。

像这样改变:

.directive('myPane', function() {
    return {
      restrict: 'E',
      transclude: true,
      scope: {
        title: '='
      },
      controller: function($scope, $timeout) {
        $scope.title = "Foo";
      },
      templateUrl: 'my-pane.html'
    };
  });