相关疑难解决方法(0)

Angular指令:在隔离范围内使用ng-model

我无法弄清楚如何定义两个自定义指令:

  1. 使用隔离范围,和
  2. 在其模板中的新范围内使用ng-model指令.

这是一个例子:

HTML:

<body ng-app="app">
  <div ng-controller="ctrl">
    <dir model="foo.bar"></dir>
    Outside directive: {{foo.bar}}
  </div>
</body>
Run Code Online (Sandbox Code Playgroud)

JS:

var app = angular.module('app',[])
  .controller('ctrl', function($scope){
    $scope.foo = { bar: 'baz' };
  })
  .directive('dir', function(){
    return {
      restrict: 'E',
      scope: {
        model: '='
      },
      template: '<div ng-if="true"><input type="text" ng-model="model" /><br/></div>'
    }
  });
Run Code Online (Sandbox Code Playgroud)

这里所需的行为是输入的值foo.bar通过指令的(隔离)范围model属性绑定到外部范围的属性.这种情况不会发生,因为模板封闭div上的ng-if指令会创建一个新范围,因此model更新的范围会更新,而不是指令的范围.通常你通过确保表达式中有一个点来解决这些ng模型问题,但我在这里看不到任何方法.我想知道我是否可以使用这样的东西作为我的指令:

{
  restrict: 'E',
  scope: {
    model: {
      value: '=model'
    }
  },
  template: '<div ng-if="true"><input type="text" ng-model="model.value" /><br/></div>'
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用......

Plunker

angularjs angularjs-directive angularjs-scope

10
推荐指数
1
解决办法
2723
查看次数