iLemming
iLemming

Reputation: 36166

watching value of inner element in directive

How can I scope some inner element's value to an arbitrary variable and watch for its changes?

//search.html
<div>
   <input type="search" class="input-medium search-query" />
</div>

angular.module('search',[])
   .directive "searchBar", ->
      restrict: "E"
      templateUrl: 'search.html'
      replace: true

Now I'd like to $watch for input's value change ('keyup') and access (get and set) current value from "outside". Can I have some arbitrary attribute and access it, like:

<div>
  <search-bar value='{{searchTerm}}' />
</div>

I hope it's clear what I'm trying to do.

Upvotes: 0

Views: 676

Answers (2)

Ivan P
Ivan P

Reputation: 1927

Jonathan's answer will create a "searchTerm" variable in the parent scope. This is unreliable, because if you put your directive in another scope (say a form) it will not be accessible outside of that form. What you should do is create "searchTerm" where you need it, and then pass it to "searchBar". If you are not using isolated scope for "searchBar" then you don't have to even pass it. If you do use isolated scope then passing would looks something like this.

angular.module('search',[])
   .directive("searchBar", function () {
      restrict: "E"
      scope: {
          searchTermInside: '=searchTerm'
      },
      templateUrl: 'search.html'
      replace: true});

And you use the directive like so:

<search-bar searchTerm="searchTermOutside" />

And in template

//search.html
<div>
   <input type="search" ng-model="searchTermInside" class="input-medium search-query" />
</div>

Upvotes: 0

Jonathan Palumbo
Jonathan Palumbo

Reputation: 6871

You can set the value of searchTerm inside your directives linking function.

   link: function(scope, element, attrs) {
        // input element
        var input= angular.element(element.children()[0]);
        input.bind('keyup', function(){
            scope.searchTerm = input.val();
        });
   }

Upvotes: 1

Related Questions