0
reportingApp.controller('tradeController', function($scope) {
    $scope.trades = [
        //{ticker: 'AAPL', shares: 100, limit: 500},
        //{ticker: 'GE', shares: -400, limit: 600},
    ];          
    $scope.addNewTrade = function () {
        console.log ('addNewTade executes');
            $scope.trades.push({ticker: "", shares: "", limit: ""});
           $("table tr:last td:first").focus();
    }

The focus() function does not work, because at the time it gets to run, the html row has not changed yet. Where should I put my focus code?

zsljulius
  • 3,813
  • 8
  • 36
  • 61
  • 4
    You shouldn't do DOM manipulation in a controller. You could make a directive, watch for changes to the scope and you could try doing a $timeout(function(){ element.focus();}); – TestersGonnaTest Jan 30 '14 at 14:32
  • See: http://stackoverflow.com/questions/14833326/how-to-set-focus-in-angularjs – Joel Skrepnek Jan 30 '14 at 14:34
  • @TestersGonnaTest I am very new to AngularJs. Directive is kinda difficult for me to understand to be honest. – zsljulius Jan 30 '14 at 14:37

1 Answers1

1

Try my custom directive:

app.directive('customAutofocus', function() {
  return{
         restrict: 'A',

         link: function(scope, element, attrs){
           scope.$watch(function(){
             return scope.$eval(attrs.customAutofocus);
             },function (newValue){
               if (newValue == true){
                   element[0].focus();
               }
           });
         }
     };
})

Use it:

custom-autofocus="$index == trades.length-1"

Set the element focused when it's the last one.

DEMO

Khanh TO
  • 48,509
  • 13
  • 99
  • 115