AngularJS input with focus kills ng-repeat filter of list

有些话、适合烂在心里 提交于 2019-12-11 19:19:59

问题


Obviously this is caused by me being new to AngularJS, but I don't know what is the problem.

Basically, I have a list of items and an input control for filtering the list that is located in a pop out side drawer.
That works perfectly until I added a directive to set focus to that input control when it becomes visible. Then the focus works, but the filter stops working. No errors. Removing focus="{{open}}" from the markup makes the filter work.

The focus method was taken from this StackOverflow post: How to set focus on input field?

Here is the code...

/* impersonate.html */
<section class="impersonate">
    <div header></div>
    <ul>
        <li ng-repeat="item in items | filter:search">{{item.name}}</li>
    </ul>
    <div class="handle handle-right icon-search" tap="toggle()"></div>
    <div class="drawer drawer-right" 
         ng-class="{expanded: open, collapsed: !open}">
        Search<br />
        <input class="SearchBox" ng-model="search.name" 
               focus="{{open}}" type="text">
    </div>
</section>


// impersonateController.js
angular
    .module('sales')
    .controller(
        'ImpersonateController',
        [
            '$scope',
            function($scope) {
                $scope.open = false;
                $scope.toggle = function () {
                    $scope.open = !$scope.open;
                }
        }]
    );

// app.js
angular
    .module('myApp')
    .directive('focus', function($timeout) {
        return {
            scope: { trigger: '@focus' },
            link: function(scope, element) {
                scope.$watch('trigger', function(value) {
                    if(value === "true") { 
                        console.log('trigger',value);
                        $timeout(function() {
                            element[0].focus(); 
                        });
                    }
                });
            }
        };
    })

Any assistance would be greatly appreciated!

Thanks! Thad


回答1:


The focus directive uses an isolated scope.

scope: { trigger: '@focus' },

So, by adding the directive to the input-tag, ng-model="search.name" no longer points to ImpersonateController but to this new isolated scope.

Instead try:

ng-model="$parent.search.name"

demo: http://jsbin.com/ogexem/3/


P.s.: next time, please try to post copyable code. I had to make quite a lot of assumptions of how all this should be wired up.



来源:https://stackoverflow.com/questions/17678813/angularjs-input-with-focus-kills-ng-repeat-filter-of-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!