简体   繁体   English

在Angular.JS中获取watch事件的DOM元素

[英]Get DOM element of watch event in Angular.JS

I have two select boxes on my web page, and when an state is chosen from the first one I use Angular to load in the options for the second. 我的网页上有两个选择框,当从第一个选择状态时,我使用Angular加载第二个的选项。 When the page first loads, the second select box has one item, Select state... and after the first item is changed, I want it to change to just Select... . 当页面第一次加载时,第二个选择框有一个项目,即Select state...并且在更改了第一个项目后,我希望将其更改为Select...

Is it possible to access the DOM element through Angular to make this change, or must I use a full-on jQuery selector as I do in this example: 是否可以通过Angular来访问DOM元素以进行此更改,还是必须像在本示例中一样使用完整的jQuery选择器:

$scope.$watch('state', function() {
    $http.get('institutions?state=' + $scope.state).success(function(institutions) {
        $scope.institutionOptions = institutions;

        // Would like to avoid this jQuery selector if possible...
        $('[name=institution_id] option:first').html('Select...');
    });
}, true);

I think you should stick to data binding as much as possible. 我认为您应该尽可能地坚持数据绑定。 Bind to $scope.message : 绑定到$scope.message

js: js:

$scope.message = "initial message"

html: 的HTML:

<select ng-model="selected" ng-options="c.o for c in options">
  <option value="">{{message}}</option>
</select>

when you receive your data, just change the message : 当您收到数据时,只需更改message

$scope.message = "select...";
$scope.options = [{o:"option1"},{o:"option2"}, {o:"option3"} ]

see this plunker: http://plnkr.co/edit/DzC5V3tlEuKZHsEVxIBx?p=preview 看到这个笨蛋: http ://plnkr.co/edit/DzC5V3tlEuKZHsEVxIBx?p=preview

You can use the angular.element api. 您可以使用angular.element api。 It uses jquery if present. 如果存在,它将使用jquery。

But you shouldn't access the DOM inside the controller. 但是您不应该访问控制器内部的DOM。 If you can't do this without manipulating DOM, try to encapsulate this code inside a directive. 如果不操作DOM就无法执行此操作,请尝试将此代码封装在指令中。

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

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