Jacob
Jacob

Reputation: 25

$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.

HTML:

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

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>

Upvotes: 0

Views: 213

Answers (1)

Brocco
Brocco

Reputation: 64843

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

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.

Upvotes: 1

Related Questions