【问题标题】:AngularJS, how to get and set a filter defined in ng-repeat from within controller?AngularJS,如何从控制器内获取和设置在 ng-repeat 中定义的过滤器?
【发布时间】:2020-03-03 05:54:42
【问题描述】:

下面的简单 HTML 块循环遍历 JSON 格式的人员对象列表 显示他们的名字和姓氏。 ng-repeat 上方的两个输入框相应地链接到基于 firstName 和 lastName 的过滤器。到目前为止一切都很好,工作正常。

我的目标是在用户离开页面时在控制器的过滤器字段中捕获用户输入,然后在他们返回页面时重新填充过滤器。当页面离开时,我可以使用 $scope.$on("$destroy"... 捕获/获取搜索字段值。但是,当我尝试设置这些字段时,$scope.search.firstName = ' John' 我收到一个错误:$scope.search 未定义。我的目标是使用 cookie 来保留然后重置过滤器字段值,但我不确定为什么该设置不起作用以及如何修复它。

<table>
    <tr>
        <td><input type="text" ng-model="search.firstName" /></td>
        <td><input type="text" ng-model="search.lastName" /></td>

    </tr>
    <tr ng-repeat="person in personList | filter:search:strict">
        <td>
            <span class="col-xs-offset-2">
                {{person.firstName}}
            </span>
        </td>


        <td>
            <span class="col-xs-offset-2">
                {{person.lastName}}
            </span>
        </td>

    </tr>
</table>

//来自控制器的片段

$scope.search.firstName = 'John'; // this does not work, returns error

$scope.$on("$destroy", function () {
    console.log($scope.search.firstName); // this works
    console.log($scope.search.lastName)); // this works
});

【问题讨论】:

    标签: html angularjs cookies filter angularjs-ng-repeat


    【解决方案1】:

    如果你得到这个TypeError: $scope.search is undefined,你应该尝试通过首先将search定义为一个对象来设置这些值。

    $scope.search = { 'firstName': '', 'lastName': ''};
    $scope.search.firstName = 'John';
    

    【讨论】:

    • 感谢您的回答,是的,这就是问题所在,我没有在控制器中定义搜索对象,因为最初我不需要访问控制器中的过滤器属性。对我来说,只需放置 $scope.search = {};这将允许访问控制器中的过滤器属性 firstName 和 lastName。
    【解决方案2】:

    在过滤器中您必须具有相同类型的对象,否则您必须按属性逐个映射

    在你的视野中尝试这种方式

    <table>
        <tr>
            <td><input type="text" ng-model="search.firstName" /></td>
            <td><input type="text" ng-model="search.lastName" /></td>
    
        </tr>
        <tr ng-repeat="person in personList | filter:{firstName: search.firstName, lastName: search.lastName}">
            <td>
                <span class="col-xs-offset-2">
                    {{person.firstName}}
                </span>
            </td>
    
    
            <td>
                <span class="col-xs-offset-2">
                    {{person.lastName}}
                </span>
            </td>
    
        </tr>
    </table>
    

    在您的视图中使用搜索变量之前初始化它在您的控制器中

    $scope.search = {firstName: '', lastName:''};
    

    【讨论】:

    • 是的,这就是原因,我没有在控制器中定义搜索对象。感谢您的回复,罗伯托也注意到了这一点。
    猜你喜欢
    • 2013-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-24
    相关资源
    最近更新 更多