javascript - AngularJs 将参数值传递给 Controller

标签 javascript angularjs angularjs-directive controller

我的 HTML:

<test-app email="hello@hotmail.com"></test-app>

我的指令:

.directive('testApp', function () {
return {
    restrict: 'E',
    scope: {
        userEmail = '@userEmail'
    },
    templateUrl: 'Form.html'
};
})

我在另一个页面中的表单:

<label> Email </label>
<input type="text" id="email">

问题:我需要获取参数值,并将其打印在文本框本身上。

我所做的:我研究了很多文章,这些文章演示了如何将指令参数传递给 Controller ​​,但它们非常复杂。

我认为下一步是:

1) 将指令参数传递给 Controller ​​,然后将 Controller 绑定(bind)到文本框,并将文本框的值设置为参数值。

2)或者还有其他方法可以做到这一点吗?

我不知道如何继续。

最佳答案

您可以使用@来使用属性字符串绑定(bind)

  1. Controller 中初始化userEmail变量

  2. 指令有一个 user-email 属性,该属性将值加载到指令的 userEmail 本地范围变量中。

  3. 使用 userEmail:'@' 允许从 Controller 到指令的字符串绑定(bind)

请参阅下面的演示:

angular.module("app",[]).directive('application', function() {
  return {
    restrict: 'E',
    scope: {
      userEmail : '@'
    },
    templateUrl: 'Form.html'
  };
}).controller("ctrl",function($scope){
  $scope.userEmail="hello@hotmail.com";
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="ctrl">
  <application user-email="{{userEmail}}"></application>
  <script type="text/ng-template" id="Form.html">
    <label>Email</label>
    <input type="text" id="email" ng-model="userEmail">
  </script>
</div>

关于javascript - AngularJs 将参数值传递给 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41551860/

相关文章:

javascript - 我如何知道 JS 代码是否使用 Google 跟踪代码管理器触发

javascript - AngularJS:在 HTML 属性中连接 Angular 变量

javascript - 如何在对象内部递归循环

javascript - 获取具有特定类名后跟数字的所有类

javascript - 为什么 jest 不 mock 这个模块?

javascript - 我如何在 ng-repeat 中使用 ng-change

javascript - 根据用户输入在 Angular 指令中设置模板或 templateUrl

angularjs - ng-quill 文本编辑器只更新一次

AngularJS 和 Typescript : How to assign a class/type as a directive's controller?

javascript - react native Webview : How to trigger function once on onScroll?