隔离指令范围,但preserve上ngModel结合指令、范围、ngModel、preserve

由网友(伪)分享简介:我将使用 NG-模型来揭露其价值指令。I have a directive that will use ng-model to expose its value.现在的问题是,这条指令有也会一塌糊涂的范围,所以我需要隔离的范围内部组件,但仍preserve NG-模型绑定到外面的世界。The question...

我将使用 NG-模型来揭露其价值指令。

I have a directive that will use ng-model to expose its value.

现在的问题是,这条指令有也会一塌糊涂的范围,所以我需要隔离的范围内部组件,但仍preserve NG-模型绑定到外面的世界。

The question is that this directive have internal components that will also mess the scope, so I need to isolate its scope, but still preserve ng-model bind to outside world.

我将如何实现这一目标?

How would I achieve this?

这是指令:

angular.module('app', []).directive('myDirective', function() {
  return {
    restrict: 'E',
    require: 'ngModel',
    link: function(scope, element, attr, ngModel) {
      // do stuff using ngModel controller
    },
    replace: true,
    template: '<div><input ng-model="userInput" /></div>'
  };
});

<my-directive ng-model="prop"></my-directive>

正如你所看到的,指令必须公开作为它的价值,但不应该暴露 userInput 在父范围,定义在&LT;输入NG模型=userInput/方式&gt;

As you can see, the directive must expose prop as its value, but should not expose userInput in the parent scope, defined in <input ng-model="userInput"/>.

我怎么能只作道具可在父范围是什么?

How would I be able to make only prop available in the parent scope?

推荐答案

通常情况下,ngModelController是为了与不创建一个新的范围指令中。我发现得到它与分离范围工作的唯一方法是在隔离范围,使用相同的名称:

Normally, ngModelController is meant to be used with directives that do not create a new scope. The only way I've found to get it to work with an isolate scope is to use the same name in the isolate scope:

scope: { prop: '=ngModel' }  // must use 'prop' here!

有关这方面的更多讨论,请参阅我的回答SO: http://stackoverflow.com/a/14792601/215945

For more discussion on this, see my SO answer: http://stackoverflow.com/a/14792601/215945

您也可以指令创建一个使用作用域的新范围:真正的。如果你这样做,那么将需要一个对象的属性,而不是原始的:例如, NG-模式='someObj.prop'。欲了解更多关于这种方法,请参阅本 http://stackoverflow.com/a/13060961/215945

You can also have the directive create a new scope using scope: true. If you do this, then prop would need to be an object property, not a primitive: e.g., ng-model='someObj.prop'. For more on this approach, see the first fiddle of this http://stackoverflow.com/a/13060961/215945

这仍然让你​​在新的指令子作用域创建自己的(新)性能,在不影响父作用域。那么,你需要知道的范围原型继承是如何工作有点 - 对象父范围界定将是该指令子作用域可见,变化多端。 基元父范围界定将是可见的,但如果你试图改变原始父的价值,你会最终创建出隐藏/阴影同名的parent属性的子属性。 (约原型继承大量的更多信息,可以发现here.)

This would still allow you to create your own (new) properties on the new directive child scope, without affecting the parent scope. Well, you need to be aware of how scope prototypal inheritance works somewhat -- objects defined on the parent scope will be visible and changeable in the directive child scope. Primitives defined on the parent scope will be visible, but if you try to change the value of a parent primitive you'll end up creating a child property that hides/shadows the parent property of the same name. (Lots more info about prototypal inheritance can be found here.)

阅读全文

相关推荐

最新文章