简体   繁体   English

$ watch不适用于angularjs中的指令属性

[英]$watch is not working on directive attribute in angularjs

Not sure what's happening, but for some reason when I type something in the input field, the $watch does not trigger handleChange function. 不知道发生了什么,但是由于某种原因,当我在输入字段中键入内容时,$ watch不会触发handleChange函数。

HTML: HTML:

<div data-suggestion-search data-search="search_string">
    <input data-ng-model="search_string"/>
</div>

JS: JS:

var suggestionSearch = function ($parse){
return {
    restrict: "A",
    transclude: true,
    scope: {
        search: '=search'
    },
    templateUrl: 'views/search.html',
    link:function(scope, lElement, attrs){
        scope.$watch("search", handleChange, true);
        function handleChange(data){
            console.log("search", scope.search);
        }
    }
}

} }

Template: 模板:

<div class="findus-search-container" ng-transclude>

</div>

I am not terribly familiar w/ how transclusion handles scopes, but I believe it creates a new scope for the directive as well as a separate scope for the content that is transcluded, so by having the same value bound to both the transclusion element and the transclusion content. 我对交错如何处理作用域并不十分熟悉,但是我相信它为指令创建了新作用域,并为被包含的内容创建了单独的作用域,因此通过将相同的值绑定到包含元素和包含内容。

Here is a working plnkr which keeps a separate scope variable in sync w/ search_string named search_string_binder which you can use to bind to your directive 这是一个有效的plnkr ,它与名为search_string_binder的search_string保持同步的单独范围变量,可用于绑定到指令

While this may not be the most eloquent solution it should get you past what was holding you up until someone w/ more transclusion knowledge can take a look at this. 尽管这可能不是最雄辩的解决方案,但它应该可以使您摆脱阻碍您前进的一切,直到有更多渗透知识的人对此进行了解。

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

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