1

I have a directive with two divs:

<div id="childContainer">
  <div id="child">
    <a class="btn btn-primary testBtn1" ng-show="!vm.hideButton">Test Button 1</a>
    <a class="btn btn-secondary testBtn2">Test Button 2</a>
  </div>
</div>

I'm trying to keep the childContainer div the same height as the child div, specifically when I hide testBtn1. Here's the watch function inside my directive's controller which should do that:

$scope.$watch(function(){
  return vm.child.height(); //vm.child is a jQuery object
}, function(){
  vm.childContainer.height(vm.child.height()); //vm.childContainer is a jQuery object
});

However, this isn't working as expected. It's as if the watch function triggers too late. You can view the issue here on my plnkr.

3
  • Change your watch to the following: $scope.$watch('vm.child.height', function(){ vm.childContainer.height(vm.child.height()); }). Commented Nov 19, 2015 at 23:19
  • Hmm. I tried that, but then the watch event didn't trigger. Maybe it has something to do with the fact that I'm using controllerAs? Commented Nov 19, 2015 at 23:22
  • Yeah gimme a sec. I just realized you're putting a watch on the return value of a function--$watch doesn't work that way. You put a watch on a variable, not a value. Commented Nov 19, 2015 at 23:24

1 Answer 1

2

$watch is supposed to take in the variable you want to monitor, not the value.

return vm.child.height(); //vm.child is a jQuery object

Here, you are returning the value of vm.child.height();. Change that to:

$scope.$watch('vm.child.height()', function(){
  vm.childContainer.height(vm.child.height()); //vm.childContainer is a jQuery object
});
Sign up to request clarification or add additional context in comments.

4 Comments

I'll repost my comment on the answer.. I tried that, but then the event didn't trigger. I also tried watching vm.child.offsetHeight and that didn't work.
@Brandon This is different from my comment. I even have it working on your plnkr.
Oh, sorry. I can't believe you got it to work. I've been trying to get around this issue for over a day. Thank you
Fresh set of eyes always helps. Make sure to use strings in your $watch statements. It's easier to read, and I'm 99% sure it's supposed to be a string anyways.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.