Newbie to AngularJS, sorry.

I want certain form inputs to have focus set on them based on certain criteria. Found that answer already with this answer (focusMe).

The problem is my form input does not show up in the model.

    <input type='text' name='school_name' ng-model='plan.school_name' focus-me="{{true}}"/>

Here is a jsfiddle to show my problem.

What am I doing wrong here??

有帮助吗?

解决方案

You defined a scope property on directive definition object. When you do that you create an isolated scope on top of the whole element, so that all other directives that are applied to that element (including ngModel) are also affected by it.

This issue has been addressed in other places (see "form element ng-model change not observered in isolate scope directive watch", "ngModel and component with isolated scope" and github issue 1924), but it's quite cumbersome to overcome.

Instead of defining an isolated scope, in this particular case you my access your focus-me attribute with attrs object (using $observe method):

var myApp = angular.module('myApp',[]).directive('focusMe', function($timeout) {
    return function(scope, element, attrs) {
        attrs.$observe('focusMe', function(value) {
            if ( value==="true" ) {
                $timeout(function(){
                    element[0].focus();
                },5);
            }
        });
    }
});

DEMO FIDDLE

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top