gpt4 book ai didi

javascript - 在 ng-repeat 中丢失 Controller 范围

转载 作者:行者123 更新时间:2023-11-30 16:51:53 25 4
gpt4 key购买 nike

嗯。 . .粗略地看一下我的代码应该可以让我不必解释我是 Angular 的新手,我敢肯定。

我正在构建一个允许搜索用户文本的应用程序,当文本输入的值发生变化时查询数据库,然后生成匹配项列表。后端很简单并且可以正常工作。在前面,我有搜索字段和结果容器:

<div id="search" ng-controller="FormController">
<input type="text" class="form-control input-lg" placeholder="Start typing . . ." ng-keypress="search()" ng-model="searchField" id="search-field">

<div id="results" class="alert alert-success">
<a href="#" ng-href="#" ng-repeat="item in items" ng-click="add(item)">
<p class="lead text-left">
<span>{{item.DisplayName}} -</span>
<span> {{item.Description}} -</span>
<span> {{item.Count}} ct. -</span>
<span> ${{item.Price}}</span>
<span class="glyphicon glyphicon-check pull-right"></span>
</p>
</a>
<h4>{{noResults}}</h4>
</div>
</div>

在我的 Controller 中调用的两个方法:

$scope.search = function()
{
$scope.$watch('searchField', function (newValue)
{
if (newValue)
{
$http.post('/search',
{
val: newValue
})
.success(function (response)
{
if (response.length > 0)
{
$scope.items = response;
$scope.noResults = '';

}
else
{
$scope.noResults = 'No Matches Found';
$scope.items = '';
}
})
.error(function (response)
{
console.log('Oooops, error: ' + response);
});
}
});
};

$scope.add = function(item)
{
console.log('added');
};

$scope.search(),虽然可能有点困惑,但可以正常工作。但是 add() 方法不会在点击时调用。我猜那时我根本不在 Controller 的范围内,但经过大量搜索后,我转向你,难倒了。我正处于“用头撞键盘并希望它神奇地工作”的阶段。

这是一个继承问题吗?

** 更新 **这是整个 Controller (按照评论中的建议删除了 $watch):

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

app.controller('FormController', ['$scope', '$http', 'toastr', function($scope, $http, toastr)
{

$scope.search = function()
{
var searchText = $scope.searchField;

$http.post('/search',
{
val: $scope.searchField
})
.success(function (response)
{
if (response.length > 0)
{
$scope.items = response;
$scope.noResults = '';

}
else
{
$scope.noResults = 'No Matches Found';
$scope.items = '';
}
})
.error(function (response)
{
console.log('Oooops, error: ' + response);
});
};

$scope.add = function(item)
{
console.log('added');
};

}]);

更新 2

Here是一个 plunker,显示一切正常,直到 add() 方法(我可能在此版本中重命名了该方法)。当然,在我的 $http 帖子中,我硬编码了一个从服务器返回的假响应。

最佳答案

CSS 问题。注释掉 CSS 的 8382 行,ugh(将#results display 设置为 none)。那就行了。你最终如何在你的 CSS 中解决这个问题是一个不同的问题。

关于javascript - 在 ng-repeat 中丢失 Controller 范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30408171/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com