AngularJS将Javascript对象传递给控制器

时间:2014-09-10 13:55:10

标签: javascript angularjs

我试图将Javascript对象传递给我的AngularJS控制器并且没有运气。

我已尝试将其传递到init函数:

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

在我的控制器方面:

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

虽然上述情况似乎无效。

或者,我尝试从我感兴趣的AngularJS控制器中提取属性,以便在内联<script>标记中使用:

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

有谁能告诉我:关于这个问题的最佳做法是什么?

我没有选择重写纯Javascript对象,因为它是第三方库的一部分。

如果我需要进一步澄清并提前感谢任何指导,请告知我们。

- JohnDoe

3 个答案:

答案 0 :(得分:4)

尝试将其设置为值:

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

然后将其注入您的控制器:

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

答案 1 :(得分:4)

由于您的对象是第三方库的一部分,因此您必须以有角度的方式将其包装。

您的选择是:

  • 如果是jquery pluging init'ed为DOM节点等,你可以创建一个directive

示例

 myApp.directive('myplugin', function myPlanetDirectiveFactory()      {
   return {
     restrict: 'E',
     scope: {},
     link: function($scope, $element) { $($element).myplugin() }
   }
});
  • 如果您需要初始化,可以使用factoryservice

例如

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

  return {
    do: function() {  obj.do() }
  }
})
  • 如果是普通的javascript对象,您可以使用value

例如

myApp.value('planet', { name : 'Pluto' } );
  • 如果它是常数(数字,字符串等),您可以使用constant

例如

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

参考此文档页面:https://docs.angularjs.org/guide/providers

此外,我强烈建议您阅读这个问题的答案:"Thinking in AngularJS" if I have a jQuery background?

答案 2 :(得分:1)

如果您通过全局范围(通过窗口)访问JSOBJ,则可以直接通过window访问它,就像在纯JavaScript中一样。

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

选项1。

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

然而,它使控制器代码无法测试。因此可以使用$window服务

选项2。

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

如果您想创建一些抽象层以使您的控制器与您获取对象的源不相关,建议定义负责获取值的服务,然后将其注入您的控制器,指令等。

选项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>

除此之外,对于简单值,您可以定义可以注入任何控制器,服务等的constantvalue

选项4。

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