AngularStrap ' bs-typeahead '的' ng-model '在作用域中不可用

`ng-model` of AngularStrap `bs-typeahead` not available in scope?

本文关键字:作用域 ng-model bs-typeahead AngularStrap      更新时间:2023-09-26

我遇到了一个问题,ng-model的值,应用到使用AngularStrap的bs-typeahead的元素,是不可访问的范围内。但是,在HTML中使用{{ var }}是可行的。

我有以下HTML:

<input type="text" placeholder="add a destination" ng-options="item as item for item in modelTypeahead" ng-model="selectedDestination" bs-typeahead data-template="templates/SrcDstTypeaheadTemplate.html">

我在控制器中初始化变量:

$scope.selectedDestination = "";

在HTML的其他地方放置{{ selectedDestination }}可以正常工作。

然而,当我做console.log($scope.selectedDestination);在我的控制器它出来作为一个空字符串。

如果我将我的初始化更新为一些东西,例如:

$scope.selectedDestination = "abc123";

<input>{{ selectedDestination }}都进行了适当的更新。我的console.log也会吐出设定值。然而,如果我提前更新输入,{{ selectDestination }}会更新,但我的console.log仍然会吐出'abc123'。

是否有我遗漏的范围问题?我不明白{{ selectedDestination }}是如何拿出正确的字符串,但console.log是拿出不同的东西。看起来我的绑定是单向的,但是AngularStrap的bs-typeahead应该是双向的(每个例子)。

你在哪里做console.log ?在此之前,你必须确保值已经改变为了显示值,你可以这样做:

$scope.watch('selectedDestination', function() { 
    console.log($scope.selectedDestination); 
});

我不确定您是否仍然遇到任何问题,但是当我最近遇到同样的问题时,我找到了一个解决方案。我几乎可以肯定,这是一个作用域问题或应用失败在AngularStrap的东西,但我不知道从哪里开始找。

真的,我没有受过足够的教育,不能给你确切的原因,这是有效的,但这是你做的:

(1)将变量更改为对象。

当你把模型和监视放在一个对象上而不是顶层变量上时,它通过指令层工作得更好。不要问我为什么....

(2)对刚刚创建的对象使用深度监视。

当您将其更改为对象时,您需要对变量使用深度监视,否则$apply和$digest将无法拾取任何更改。这是因为默认情况下,将检查值是否"引用"相等,而不是"值"相等。这是因为对象的"引用"没有改变,只有它的值改变了。但是要小心使用这种深度比较,因为额外的工作可能会导致大量开销。

下面是一个使用AngularStrap的typeahead的例子:

$scope.selectedDestination = {};
~~~
<input type="text" placeholder="add a destination" ng-options="item as item for item in modelTypeahead" ng-model="selectedDestination.destination" bs-typeahead data-template="templates/SrcDstTypeaheadTemplate.html">
~~~
$scope.$watch('selectedDestination', function(value) {
  console.log('selectedDestination', $scope.subComponent);
}, true); //here we need to tell the watch to do a deep watch

编辑我已经把我的问题追溯到一些事情,但它的一部分是$render函数。我会继续调查的。好运!