简体   繁体   English

Ng-if on指令使用双向绑定覆盖函数

[英]Ng-if on directives with two way bindings that override functions

I've set up a directive that will take in a function from the parent controller as one of it's attributes. 我已经设置了一个指令,它将从父控制器中获取一个函数作为其中一个属性。 This function will be replaced by the directives controller and will be accessible by the parent controller by using the passed function. 此函数将由指令控制器替换,并且父控制器可以使用传递的函数访问该函数。 The issue I'm running into is when placing an ng-if attribute on the directive the passed in function is not being replaced anymore. 我遇到的问题是在指令上放置ng-if属性时传入的函数不再被替换。 What causes this and how would I go about fixing this issue? 是什么导致这个问题,我将如何解决这个问题? I've attached an example 我附上了一个例子

https://jsfiddle.net/dh7jt1zg/1/ https://jsfiddle.net/dh7jt1zg/1/

    <div class="parent" ng-controller="pCtrl">
        <h3>Parent - with ng-if</h3>
        <div>{{parentHelloWorld()}}</div>
        <child ng-if="testBool" rep-fun="parentHelloWorld"></child>
    </div>
    <br/>
    <div class="parent" ng-controller="pCtrl2">
        <h3>Parent2 - without ng-if</h3>
        <div>{{parentHelloWorld()}}</div>
        <child rep-fun="parentHelloWorld"></child>
    </div>

Use ng-show instead of ng-if . 使用ng-show代替ng-if ng-if causes element to remove from the DOM. ng-if导致元素从DOM中删除。

I think you'd be better off to create a service instead of replacing the function in the child controller. 我认为你最好创建一个服务而不是替换子控制器中的函数。 That seems kind of messy to me. 这对我来说似乎有些混乱。

Personally, I'd use a service to register the function and then you can use that same service from the parent controller to call it. 就个人而言,我使用服务注册该功能,然后您可以使用父控制器中的相同服务来调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM