AngularJS,如何从控制器内部获取并设置ng-repeat中定义的过滤器?

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

我的目标是在用户离开页面时在控制器的过滤器字段中捕获用户输入,然后在返回页面时重新填充过滤器。当页面离开时,我可以使用$ scope。$ on(“ $ destroy” ...来捕获/获取搜索字段值。但是,当我尝试设置这些字段时,$ scope.search.firstName ='约翰,我收到一个错误消息:$ 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
});
yuanpeichen 回答:AngularJS,如何从控制器内部获取并设置ng-repeat中定义的过滤器?

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

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

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

在您看来以这种方式尝试

<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:''};
本文链接:https://www.f2er.com/3150181.html

大家都在问