我有一个Javascript变量,我想通过元素指令传递它。我在ng-init
的帮助下这样做,但我的客户告诉我这会导致他们的 ServiceNow 设置出现问题,所以我必须通过指令参数来完成。
每当我尝试时,我都会收到错误。这是我的代码:
应用程序.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/