Josef_the_third
Josef_the_third

Reputation: 121

Angular have an element show up when not in a angular template

I have an input box with a class directive on it. Within the input box delement, I want to have another element with an ng-show. How do I make it so that a scope variable is available on the inner element?

<div class="medium-2">
   <label>Age:</label> 
</div>
<div class="medium-10">
   <input type="text" class="form-control pop-up-variables" name="age" error-message="ageErrorMessage" required>
   </input>
</div>

The block I want to be able to add is this:

<input ng-show="showInnerBlock" class="variable-dropdown" type="text" uib-typeahead="number as number for number in numbers | filter:$viewValue" ng-model="selectedAttribute" placeholder="Choose variable"> 
</input>

I don't want to return it as a template in the directive because I dont want to replace the block that the directive is on, but I don't know how to add it correctly to the DOM.

The simple JS looks like:

  app.directive('popUpVariables', function() {

    return {
      restrict: 'C',
      controller: function($scope) {
        $scope.numbers = ['One', 'Two', 'Three', 'Four', 'Five'];
        },
      link: function (scope, element, attrs, ngModelCtrl) {
        element.on('keypress', function(event) {
          if (event.which === 64) {
            // This is where I want to show the second input
            scope.showInnerBlock = true;
          }
        });
      }
   }
})

Upvotes: 1

Views: 57

Answers (1)

charlietfl
charlietfl

Reputation: 171690

Events outside of angular context that chnge scope must notify angular to run digest to update view.

if you used ng-keypress it would do it internally otherwise use $apply or $timeout

link: function (scope, element, attrs, ngModelCtrl) {
    element.on('keypress', function(event) {
      if (event.which === 64) {            
        scope.showInnerBlock = true;
        $scope.$apply()
      }
    });
  }

Upvotes: 1

Related Questions