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.
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.