javascript - 将 Javascript 变量传递到指令参数中

标签 javascript angularjs

我有一个 Javascript 变量,我想通过元素指令传递它。 我是在 ng-init 的帮助下完成的,但我的客户告诉我这会导致他们的 ServiceNow 设置出现问题,所以我必须通过指令参数来完成。

每当我尝试时都会出错。这是我的代码:

APP.JS

//directive decleration 
app.directive('myDirective', function(){
  var directive = {};
  directive.restrict = 'E';
  directive.scope = {
    myParam: '='
  }; 
  directive.template = '<div>{{myParam}}</div>';
  return directive;
}) ;

HTML

<script>
var temporary_var = 'Helloworld';
</script>
<div ng-controller="progressController">
<my-directive my-param="temporary_var"></my-directive>
</div>

正如您所看到的,我现在刚刚传递了一个普通字符串,但我将通过此指令参数传递数组或对象。这只是一个例子。我也尝试过传递数组和对象,但没有运气。

最佳答案

试试这个:

<script>
  var temporary_var = 'Helloworld';

</script>
<div ng-controller="progressController">
  <my-directive my-param="param"></my-directive>
</div>
<小时/>
 angular.module('components', []).directive('myDirective', function() {
    return {
      restrict: 'E',
      scope: {
        myParam: '='
      },
      template: '<div>Hi {{myParam}}</div>'
     }
 });
    angular.module('myApp', ['components']).controller('progressController', ['$scope', '$window',             function($scope, $window) {
       $scope.param = $window.temporary_var; //This is the key
   }]);

演示:https://jsfiddle.net/lotusgodkk/26gnybqf/1/

关于javascript - 将 Javascript 变量传递到指令参数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57248923/

相关文章:

javascript - CSS 条件元素,XHTML

javascript - 如何检测用户使用浏览器中的“后退”按钮打开页面?

angularjs - 获取 JSON 格式的 Azure Blob 数据

javascript - 尽管其他 Controller 和服务正常工作,但仍出现未知提供程序错误

javascript - 如何在 Angular JS 中正确使用 ng-cloak?

javascript - AngularJS - 立即应用指令,格式化货币

javascript - 如何使用 reactjs 和 material ui 将 textField 添加到表中的特定行 onclick of a button

javascript - 字符串到 JavaScript 数组,元素作为数组

javascript - 如何在使用 ng-include 加载部分内容之前解决 XHR 请求

javascript - 使用 php 动态更改 html 表格单元格内容