【问题标题】:Trouble $watching model being passed to parent directive through directive attribute麻烦 $watching 模型通过指令属性传递给父指令
【发布时间】:2013-07-08 16:11:01
【问题描述】:

在回答另一个问题时,我意识到我无法通过其属性将子模型传递给父指令。

鉴于此设置:

<form child-watch mod="inputModel" name="form"><!--ignore creepy directive name-->
  <input type="text" name="one" ng-model="inputModel.one">
  <input type="text" name="two" ng-model="inputModel.two"><br/>
  <input type="submit" ng-disabled="form.$pristine">
  <p>Original Model: {{original}}</p>
  <p>Isolate Scope Model: {{isolate}}</p>
</form>

如何通过其属性$watch 指令中的 inputModel,并查看子项所做的更改?如果我使用隔离作用域,它只会 $watch UP 到父模型,现在不受隔离子模型的影响。

显然这行不通,但你可以看到我要去的方向:

app.directive('childWatch', function(){
    return {
        // removing the isolate scope allows parent scope.inputModel to update
        scope:{
            mod: "="
        },
        link: function(scope, element, attrs){


            //this does not reflect change upon the parent scope.inputModel
            //if using isolate scope.  AND, I don't want to $watch a specific
            // model, because the directive needs to be reusable.  It needs to watch
            // an attribute that references the model.
            scope.$watch('inputModel', function(val){
                scope.original = val;        
            },true)


            //this only has access to the parent scope.inputModel
            scope.$watch('mod', function(i){
                scope.attribute = i;            
            }, true)
        }    
    }
})

为了使指令可重复用于不同的模型,我不能只看一个特定的模型。它需要监视引用模型的属性。我不确定这是可能的。有什么想法吗?

Here's the plunk我在搞砸。

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    使用隔离作用域时,只有scope: { ... } 中引用的那些属性可用于视图和指令。在任何地方使用mod,它就会起作用:

    <form child-watch mod="inputModel" name="form">
      <input type="text" name="one" ng-model="mod.one">
      <input type="text" name="two" ng-model="mod.two"><br/>
      <p>Model in attribute: {{attribute}}</p>
      <p>Original model: {{mod}}</p>
    </form>
    

    Plunker

    【讨论】:

    • 嘿。我认为自己没有这样做,在页面上考虑了多个表单/指令,它们不能共享相同的模型。但是隔离范围使这项工作。谢谢。
    • 在我检查之前 - 让我问一下 - 有没有办法在没有隔离范围的情况下完成这个?只看 $eval'd 属性本身?
    • @rGil,是的,您可以使用 $parse -- 请参阅 stackoverflow.com/a/15725402/215945
    • 这实际上是我正在寻找的答案。我缺少的部分是(scope)$parse(attr.whatever) 之后。 updated plunker
    • 有趣的是,您可以 $watch 一个经过 $parsed 的对象,但不是 $eval'd 的对象。
    猜你喜欢
    • 2015-10-27
    • 1970-01-01
    • 2016-05-23
    • 2013-04-23
    • 1970-01-01
    • 1970-01-01
    • 2016-05-10
    • 1970-01-01
    • 2015-11-29
    相关资源
    最近更新 更多