AngularJS – ngSelected 指令

angularjsweb developmentfront end technology更新于 2026/1/7 2:07:17

AngularJS 中的 ngSelected 指令 将元素上的 selected 属性设置为 True。我们也可以在 ngSelected 中编写一个表达式,其唯一条件是该表达式的计算结果为 True。

由于 selected 属性内部无法使用插值,因此此特殊指令是必需的。

语法

<element ng-required="expression">..content..</element>

示例 − ngSelected 指令

创建文件"ngSelected.html"在您的 Angular 项目目录中并复制粘贴以下代码片段。

<!DOCTYPE html>
<html>
   <head>
      <title>ngSelected Directive</title>

      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
      </script>
   </head>

   <body ng-app style="text-align: center;">
      <h1 style="color: green;">
         Welcome to Tutorials Point
      </h1>
      <h2>
         AngularJS | ngSelected Directive
      </h2>
      <label>Check me to select: <input type="checkbox" ng-model="selected" /></label><br />
      <select aria-label="ngSelected demo">
         <option>Welcome!</option>
         <option id="greet" ng-selected="selected">Welcome to Tutorials Point!</option>
      </select>
   </body>
</html>

输出

要运行上述代码,只需打开您的文件并将其作为普通 HTML 文件运行即可。您将在浏览器窗口中看到以下输出。


相关文章