我有一个 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
}]);
关于javascript - 将 Javascript 变量传递到指令参数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57248923/