【问题标题】:In AngularJS can I use the ng-model and the ng-bind only in the view without involving the use of a controller?在 AngularJS 中,我可以只在视图中使用 ng-model 和 ng-bind 而不涉及使用控制器吗?
【发布时间】:2023-03-28 03:12:01
【问题描述】:

我对 AngularJS 很陌生,我发现这个例子与 ng-modelng-bind 指令有关:

<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="page" tagdir="/WEB-INF/tags" %>

<page:angular-template>

    <jsp:attribute name="title">
        AngularJS ng-bind ng-model
    </jsp:attribute>

    <jsp:body>                  

    <div ng-app>

    <h1>AngularJS ng-bind ng-model</h1>
    <div>
        <table class="table table-striped">
          <tr>
            <td><b>Username:</b></td> <td><input type="text" ng-model="username"/></td>
          </tr>
          <tr>
            <td><b>Password:</b></td> <td><input type="text" ng-model="passwords"/></td>
          </tr>
          <tr>
            <td><b>authorization:</b></td>  <td><input type="text" ng-model="authorization"/> </td>
          </tr>
        </table>
    </div> 

    Hi {{ username }} welcome to Java Spring MVC Integrated with AngularJS by Google and HTML5<br/>
    You password is {{ passwords }} <br/>
    and login as <span ng-bind="authorization"></span> <br/>
    </div>


    </jsp:body>
</page:angular-template>

所以在我看来,基本上它只显示一个表单,并且每个 input 元素都通过 ng-modelmodel 属性 相关联strong> 属性。

然后,在同一页面中,我可以通过诸如 {{ username }} 之类的 AngularJS 表达式或使用 ng-bind 来检索这些模型属性的值> 指令。比如:

<span ng-bind="authorization">

这意味着在这个范围内,它应该显示插入到具有 ng-model="authorization"

的输入标签中的值

我的推理正确吗?

我的疑问是:在使用 AngularJS 时,我可以避免通过控制器吗?我已经看到如何将这些值放入 $scope 服务的属性中。

例如,输入标签 ng-model$scope 服务的特定属性(以这种方式将视图关联到控制器)。

我可以避免通过控制器吗?

【问题讨论】:

    标签: javascript angularjs angularjs-directive angularjs-scope angular-ngmodel


    【解决方案1】:

    如果我的问题是对的,是的,你是对的,而且你做得很好。

    这就是 Angular 的魔力。 DOM-wise 你有一个“最小的应用程序”,甚至不使用控制器。

    这样你就可以让 DOM 显示你正在输入的数据。

    当然,为了处理他的数据或对它们做一些事情,你需要一个控制器,但你甚至可以使用ng-init 并设置authorization 来设置一个值而不通过控制器随心所欲。

    <div ng-init="authorization='yeah'"></div>
    

    ng-init doc

    所以,是的,您可以在没有控制器的情况下使用 Angular。

    (希望我得到你的问题..)

    【讨论】:

    • 意大利人很可爱,但是OP懂英文,本站首选。另外,如果不通过控制器,我们如何访问模型对象?
    • 对不起,你是对的,我会解决的。我猜他是在问他是否可以在没有控制器的情况下读取这些变量。对我来说是可行的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-02
    • 1970-01-01
    • 2014-09-30
    • 2017-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多