如何在element.find()中的最后一个元素上指定焦点函数

时间:2015-04-17 10:11:39

标签: angularjs angularjs-directive

通过执行此操作,我能够在第一个输入元素上插入新的输入元素。 这是小提琴。

http://jsfiddle.net/nr0tbh86/1/

html代码:

<div ng-app="myApp" ng-controller="MyCtrl">
    <div add-input>
        <input type="text" placeholder="focus on this"><br>
    </div>
</div>

Controller.js:

var app = angular.module('myApp', []);

app.controller('MyCtrl', ['$scope', function ($scope) {
    // Define $scope.telephone as an array
    $scope.inputFeild = [];
    // Create a counter to keep track of the additional telephone inputs
    $scope.inputCounter = 0;

    // This is just so you can see the array values changing and working! Check your console as you're typing in the inputs :)
    $scope.$watch('telephone', function (value) {
        console.log(value);
    }, true);
}]);

// I've created this directive as an example of $compile in action. 
app.directive('addInput', ['$compile', function ($compile) { // inject $compile service as dependency
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            // click on the button to add new input field
            element.find('input').bind('focus', function () {
                // I'm using Angular syntax. Using jQuery will have the same effect
                // Create input element
                var input = angular.element('<div><input type="text" ng-model="inpuTfeild[' + scope.inputCounter + ']"></div>');
                // Compile the HTML and assign to scope
                var compile = $compile(input)(scope);

                // Append input to div
                   element.append(input);

                // Increment the counter for the next input to be added
                scope.inputCounter++;
            });
        }
    }
}]);

但我真正需要的是在聚焦最后输入时生成输入。

1 个答案:

答案 0 :(得分:1)

请尝试使用()而不是append()。 append()添加到div的内部。随着追加新的div被添加到第一个看起来不正确的div中。

<div add-input="">
    <input type="text" placeholder="focus on this"><br>
    <div add-input="" class="ng-scope">
        <input type="text" ng-model="inputFeild[0]" class="ng-pristine ng-valid">
    </div>
</div>