简体   繁体   English

AngularJS将Javascript对象传递给控制器

[英]AngularJS pass Javascript object to controller

I'm trying to pass a Javascript object into my AngularJS controller and having no luck. 我正在尝试将Javascript对象传递给我的AngularJS控制器并且没有运气。

I've tried passing it into an init function: 我已经尝试将它传递给init函数:

<div ng-controller="GalleryController" ng-init="init(JSOBJ)">

And on my controller side: 在我的控制器方面:

$scope.init = function(_JSOBJ)
{
    $scope.externalObj = _JSOBJ;
    console.log("My Object.attribute : " + _JSOBJ.attribute );
};

Though the above doesn't seem to work. 虽然上述似乎不起作用。

Alternatively, I've tried pulling the attribute from the AngularJS controller that I am interested in for use in an inline <script> tag: 或者,我尝试从我感兴趣的AngularJS控制器中提取属性,以便在内联<script>标记中使用:

var JSOBJ.parameter = $('[ng-controller="GalleryController"]').scope().attribute ;
console.log("My Object.parameter: " + JSOBJ.attribute );

Can anyone tell me: what is the best practice regarding this? 谁能告诉我:关于这个的最佳做法是什么?

I don't have the option to rewrite the plain Javascript object as it is part of a 3rd party library. 我没有选择重写普通Javascript对象,因为它是第三方库的一部分。

Let me know if I need to provide further clarification and thanks in advance for any guidance! 如果我需要进一步澄清并提前感谢任何指导,请告诉我们!

-- JohnDoe - 约翰多

Try setting it as a value: 尝试将其设置为值:

angular.module('MyApp')
    .value('JSOBJ', JSOBJ);

Then inject it into your controller: 然后将其注入您的控制器:

angular.module('MyApp')
    .controller('GalleryController', ['JSOBJ', function (JSOBJ) { ... }]);

Since your object is a part of third-party library you have to wrap it app in something angular. 由于您的对象是第三方库的一部分,因此您必须以有角度的方式将其包装。

Your options are: 你的选择是:

  • if it is jquery pluging init'ed for a DOM node etc you can create a directive 如果是jquery pluging init'ed为DOM节点等,你可以创建一个directive

example

 myApp.directive('myplugin', function myPlanetDirectiveFactory()      {
   return {
     restrict: 'E',
     scope: {},
     link: function($scope, $element) { $($element).myplugin() }
   }
});
  • if it is something you need to init you can use factory or service 如果它是您需要初始化的东西,您可以使用factoryservice

example

myApp.service(function() {
  var obj = window.MyLib()

  return {
    do: function() {  obj.do() }
  }
})
  • if it is plain javascript object you can use value 如果它是普通的javascript对象,你可以使用value

example

myApp.value('planet', { name : 'Pluto' } );
  • if it is constant ( number, string , etc) you can use constant 如果它是常量(数字,字符串等),你可以使用constant

example

myApp.constant('planetName', 'Greasy Giant');

Reference to this doc page: https://docs.angularjs.org/guide/providers 参考此文档页面: https//docs.angularjs.org/guide/providers

Also I strongly encourage you to read answer to this question: "Thinking in AngularJS" if I have a jQuery background? 另外,我强烈建议您阅读这个问题的答案: “如果我有jQuery背景,请在AngularJS中思考”?

If you have JSOBJ accessible via global scope (via window), than you can access it through window directly as in plain JavaScript. 如果您可以通过全局范围(通过窗口)访问JSOBJ ,那么您可以直接通过window访问它,就像在纯JavaScript中一样。

<script>
   ...
   window.JSOBJ = {x:1};
   ...
</script>

Option 1. 选项1。

<script>
  angular.module('app',[]).controller('ctrl', ['$scope', function($scope) {
    $scope.someObject = window.JSOBJ;
  }]);
</script>

However it makes the controller code not testable. 但是它使控制器代码无法测试。 Therefore $window service may be used 因此可以使用$window服务

Option 2. 选项2。

<script>
  angular.module('app',[]).controller('ctrl', ['$scope', '$window', function($scope, $window) {
    $scope.someObject = $window.JSOBJ;
  }]);
</script>

If you want to make some abstraction layer to make your controller agnostic for the source from where you get the object, it is recommended to define service which is responsible for fetching value and then inject it to your controllers, directives, etc. 如果您想创建一些抽象层以使您的控制器与获取对象的源不相关,则建议定义负责获取值的服务,然后将其注入您的控制器,指令等。

Option 3. 选项3。

<script>
  angular.module('app',[])
    .service('myService', function() {
      var JSOBJ = ...; // get JSOBJ from anywhere: localStorage, AJAX, window, etc.
      this.getObj = function() {
        return JSOBJ;
      }
     })
    .controller('ctrl', ['$scope', 'myService', function($scope, myService) {
      $scope.someObject = myService.getObj();
    }]);
</script>

Besides of it, for simple values you can define constant or value that may be injected to any controller, service, etc. 除此之外,对于简单值,您可以定义可以注入任何控制器,服务等的constantvalue

Option 4. 选项4。

<script>
  angular.module('app',[]).
    value('JSOBJ', JSOBJ).
    controller('ctrl', ['$scope', 'JSOBJ', function($scope, JSOBJ) {
      $scope.someObject = JSOBJ;
    }]);
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM