1

I have a form field (input text) with an ng-if being false at the begining. At some point the ng-if value become true.

When this happen, I want to execute some javascript which manipulate the DOM. To keep it simple, let's say that I need to select the input value and focus the field.

<input type="text" ng-value="foo" ng-if="show" onshow="doSomething()"/>
<button ng-click="toggle()"></button>

The JavaScript

ctrl.foo = "bar";
ctrl.show = false;

ctrl.toggle = function(){
    ctrl.show = !ctrl.show;
}

I know that it looks like a "non-angular approach", but here I think the action is not model related.

1
  • you could create a directive that and place it on your input like : do-something="show". When show is true, the directive runs. It would be similar to ng-if since when show is true, ng-if renders the html. Commented Oct 2, 2015 at 8:21

1 Answer 1

3

Since the ng-if directive execute the template each time show become true, you can use ng-init for that. See the following snippet and replace alert('test); by anything you want.

angular.module('test', []).controller('test', function($scope, $element) {

  $scope.show = false;
 
  $scope.toggle = function() {
    $scope.show = !$scope.show;
  };
  
  $scope.init = function() {
    alert($element.find('input').val());
  };
  
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="test">
  <div ng-controller="test">
    <input type="text" value="foo" ng-if="show" ng-init="init()" />
    <button ng-click="toggle()">Toggle</button>
  </div>
</div>

Sign up to request clarification or add additional context in comments.

4 Comments

That's smart! But as init is an angular function, it shows me the model context and not the dom (input tag), or at least I don't know how to acces it. If possible that way, can you update your init function to execute focus() on the input dom object?
I am still not convinced. $element is the controller dom element. In my real-life case, my controller contains a two dimensional dataset, so to reach the specific element, I would have to generate unique id's for each and search. It really looks the wrong way to search back the element that trigged the event from the outer controller context, even if it is doable.
In this case you'll have to create your own directive to replace ng-init
And that directive would be able to reach the input element directly? How?

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.