Scoping issue when setting ngModel from a directive

后端 未结 2 1201
闹比i
闹比i 2021-01-26 01:13

I have a directive which looks something like:

var myApp = angular.module(\'myApp\',[])
    .directive(\"test\", function() {
      return {
        template: \'         


        
2条回答
  •  时光说笑
    2021-01-26 01:58

    All you need to do is add scope: true to your directive hash. That makes a new inheriting child scope for each instance of your directive, instead of continually overwriting "setValue" on whatever scope is already in play.

    And you're right about isolate scope. My advice to newbies is just don't use it ever.

    Response to comment:

    I understand the question better now. When you set a value via an expression, it sets it in the most immediate scope. So what people typically do with Angular is they read and mutate values instead of overwriting values. This entails containing things in some structure like an Object or Array.

    See updated fiddle:

    http://jsfiddle.net/kMybm/20/

    ("foo" would normally go in a controller hooked up via ngController.)

    Another option, if you really want to do it "scopeless", is to not use ng-click and just handle click yourself.

    http://jsfiddle.net/WnU6z/8/

提交回复
热议问题