从指令更新控制器范围变量

时间:2015-03-04 13:39:39

标签: angularjs angularjs-directive angularjs-scope

我想通过转换其内容来制作一个行为类似于容器的指令。我的HTML看起来像这样

<test>
    <input type="text" ng-model="name" />
    <button ng-click="alertName()">Alert</button>
</test>

控制器和指令是这样的

angular.module('app', [])
  .controller('TestCtrl', function($scope) {
    $scope.name = 'Eric Cartman';

    $scope.alertName = function() {
      alert($scope.name);
    };
  })
  .directive('test', function() {
    return {
      restrict: 'E',
      template: '<div ng-transclude></div>',
      transclude: true,
      replace: true,
      link: function($scope, elem, attr, ctrl) {

      }
    };
  });

当页面加载时,我看到了Eric Cartman&#39;在文本框中,当我点击“提醒”时按钮我看到&#39; Eric Cartman&#39;在对话框中。到这里一切都很好。

问题是当我更改文本框中的名称并点击“警告”时。按钮它仍然警告&#39; Eric Cartman&#39;。我哪里错了?

Here is the Plunker

1 个答案:

答案 0 :(得分:2)

这是由于范围的原型继承和绑定变量是“顶级”(即ng-model="name",而不是ng-model="model.name")。

只需将值包装在对象中:

// controller:
$scope.model = { name: 'Eric Cartman' };
// do not forget the alert!

当然要正确绑定它:

<input type="text" ng-model="model.name" />

典型的继承是一个让人们在第一次接触它时感到困惑的话题;我甚至没有试图在这里解释这个概念,网上有很多来源。你可以研究它,或者只是接受我的话,永远不要使用“顶级”双向绑定