简体   繁体   English

使用AngularJS watch获取下拉列表中选定的项目不起作用

[英]Using AngularJS watch to get drop-down's selected item not working

Following up from AngularJS : Why my watch is not working AngularJS跟进:为什么我的手表不起作用

function myController($scope, $http) {

    $scope.abc = abcValueFromOutsideOfMyController;    

    $scope.getAbcCnt= function()
    {
        url2 = baseURL + '/count/' + $scope.abc;

        $http.get(url2).success(function (data) {
            $scope.abcCnt = data.trim();
        });
    };

    $scope.$watch('abc',getAbcCnt);
}

Why I get undefined error on $scope.abc. 为什么我在$ scope.abc上遇到未定义的错误。

abcValueFromOutsideOfMyController is set by selecting element through a drop down. 通过下拉选择元素来设置abcValueFromOutsideOfMyController。 It will be undefined initially but as soon as dropdown is selected, the value will be something other than undefined, I verified in console, I get some value. 它最初是未定义的,但是一旦选择了下拉列表,该值将是未定义的值,我在控制台中验证,我得到一些价值。

Drop down code is here 下拉代码就在这里

$(document).on('click', '.dropdown-menu li a', function () {

    selectedItem = $(this).text();
    $("#selectedItem").text(selectedItem);
    abcValueFromOutsideOfMyController= selectedItem.trim();
    console.log(abcValueFromOutsideOfMyController);
});

Here is my html 这是我的HTML

<div class="dropdown btn">

    <div id="collectiondropDown" class="dropdown-toggle" id="dLabel" role="button" data-toggle="dropdown"
         data-target="#" >
        &nbsp;<span id="selectedItem" ng-model="abc">Items</span>
        <b class="caret"></b>
    </div>

    <ul id="dropDownUL" class="dropdown-menu pull-left" role="menu" aria-labelledby="dLabel">
    </ul>
</div>

I am new to AngularJS, let me know if there is some fundamental concept I am missing and above is not possible to do. 我是AngularJS的新手,请告诉我是否有一些我缺失的基本概念,以上是不可能的。

$scope.abc , as you mention, is undefined at some point and is probably being accessed during this time. 正如您所提到的, $scope.abc在某些时候是未定义的,并且可能在此期间被访问。 It looks like you're setting $scope.abc via jQuery, you should be doing it via the ng-model within AngularJS. 看起来你正在通过jQuery设置$scope.abc ,你应该通过AngularJS中的ng-model来完成它。

First, just define a stub for your variable: 首先,只需为您的变量定义一个存根:

$scope.abc = "";

Then in your HTML: 然后在你的HTML中:

<input ... ng-model="abc" ... />

This will bind the input element (works on selections too) to the backend variable. 这会将输入元素(也适用于选择)绑定到后端变量。 As the user makes selections it will magically update in your code, and if you update the variable in your code it will update in the view too! 当用户进行选择时,它将在您的代码中神奇地更新,如果您更新代码中的变量,它也将在视图中更新!

You can read more about ng-model here: http://docs.angularjs.org/api/ng.directive:ngModel 你可以在这里阅读更多关于ng-model信息: http//docs.angularjs.org/api/ng.directivengModel

UPDATE UPDATE

Here is another option that works with Twitter Bootstrap's Dropdown. 这是另一个与Twitter Bootstrap的Dropdown一起使用的选项。 It might not be the most "best" solution, but it is the first one that came to mind. 它可能不是最“最好”的解决方案,但它是第一个浮现在脑海中的解决方案。

In your elements, you can add an ng-click directive and call a function in your controller. 在元素中,您可以添加ng-click指令并在控制器中调用函数。 That controller then sets a variable that is used as the title for the button. 然后该控制器设置一个变量,用作按钮的标题。 In that case you don't use ng-model , you just include the variable in a {{ }} container. 在这种情况下,您不使用ng-model ,只需将变量包含在{{ }}容器中即可。

Your HTML would look something like: 您的HTML看起来像:

<div class="dropdown btn">
  <div id="collectiondropDown" class="dropdown-toggle" id="dLabel" role="button" data-toggle="dropdown" data-target="#" >
    <span>{{ selectedItem }}</span>
    <b class="caret"></b>
  </div>

  <ul id="dropDownUL" class="dropdown-menu pull-left" role="menu" aria-labelledby="dLabel">
    <li ng-click="OnItemClick('Option 1')">Option 1</li>
    <li ng-click="OnItemClick('Option 2')">Option 2</li>
    <li ng-click="OnItemClick('Option 3')">Option 3</li>
  </ul>
</div>

... and your JavaScript: ......和你的JavaScript:

function DropdownCtrl($scope) {

  $scope.selectedItem = "Items";

  $scope.OnItemClick = function(event) {
    $scope.selectedItem = event;
  }
}

I've created a Plunker of the example. 我已经创建了一个示例的Plunker。 You can find it here: http://plnkr.co/edit/JrKJKxfG6aYiLHfR4pGE?p=preview 你可以在这里找到它: http//plnkr.co/edit/JrKJKxfG6aYiLHfR4pGE?p = preview

I have found an even better solution This is by far the simplest and least code solutions 我找到了一个更好的解决方案这是迄今为止最简单和最少的代码解决方案

 <ul id="dropDownUL" class="dropdown-menu pull-left" role="menu" aria-labelledby="dLabel">
   <li ng-click="abc = 'value1'">Value1</li>
   <li ng-click="abc = 'value2'">Value2</li>
 </ul>

There is also another way if you are loading them dynamically 如果要动态加载它们,还有另一种方法

  <ul id="dropDownUL" class="dropdown-menu pull-left" role="menu" aria-labelledby="dLabel">
   <li ng-repeat="value in values" ng-click="abc = value">{{value}}</li>
  </ul>

Notice the single ticks if its a static string value and no ticks if its dynamic. 如果它是一个静态字符串值,请注意单个滴答,如果它是动态的,则不勾选。

I am able to get the selected item from the dropdown like below: 我可以从下拉列表中获取所选项目,如下所示:

<body ng-app="app" ng-controller="ctrl">
<p>Id:{{id}}</p>
<select ng-model="id" ng-options="val.id as val.name for val in options">
</select>
<script>
angular.module("app",[])
  .controller("ctrl",['$scope',function($scope){
    $scope.options = [
      {id:1, name:'First'},
      {id:2, name:'Second'}
    ]
    $scope.$watch('id');
  }])
 </script>
</body>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM