如何防止模型碰撞



在本例中,我再现了两个指令对ng-model使用相同名称并且导致其输入中的值链接的情况。

http://plnkr.co/edit/aF5DtMVyQ27Rgb7ximEw?p=preview

COde:

var app = angular.module('app', []);
app.directive('formOne', function() {
  return {
    'restrict': 'E',
    'template': "<form name='formOne'><input type='text' ng-model='myValue'></form>"
  };
});
app.directive('formTwo', function() {
  return {
    'restrict': 'E',
    'template': "<form name='formTwo'><input type='text' ng-model='myValue'></form>"
  };
});
app.controller('MyController', function($scope) {
  //stuff
});

HTML:

  <div ng-controller='MyController'>
    <h1>Input something</h1>
    <form-one></form-one>
    <form-two></form-two>
  </div>

防止这种事情发生的常规方法是什么?我们将非常感谢与官方来源的链接。也可以有一些官方的命名约定-

这正是您希望在指令中使用隔离作用域的原因。

app.directive('formOne', function() {
    return {
        scope: true,
        restrict: 'E',
        template: "<form name='formOne'><input type='text' ng-model='myValue'>{{myValue}}</form>"
    };
});

固定演示:http://plnkr.co/edit/IZWZhwtfclZKMnnNNFA9?p=preview

使用一个独立的作用域,因此任何模型都只适用于该作用域。前面的解决方案将问题带到了"如何从指令中获取数据?",有两种解决方案:

  • 使用带=bindings的隔离作用域(请参阅$compile,作用域部分)
  • 使用事件发送信息

最新更新