如何在AngularJS中创建元素时执行外部函数?

时间:2015-05-16 11:56:42

标签: javascript angularjs

我想在AngularJS中创建每个项目时从外部库运行一些函数。我该怎么办?你可以在下面看到我的应用程序的代码。

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
  $scope.blocks = [
    {name: 'item #1'},
    {name: 'item #2'}
  ];
});
<script src="https://code.angularjs.org/1.4.0-rc.2/angular.js"></script>
<script>
  // this function is provided by external library
  // I want to setup each block in ng-repeat
  // it manipulated DOM
  function setupBlock(elm, name) {
    elm.innerHTML = name + ' [ready]';
  }
</script>

<body ng-controller="MainCtrl" ng-app="app">
  <div ng-repeat="block in blocks">{{block.name}}</div>
</body>

3 个答案:

答案 0 :(得分:1)

创建一个带有参数name的指令:

.directive('myDirective', function() {
  return {
    restrict: 'A',
    scope: {
      name: '='
    },
    link: function(scope, elm, attrs) {
      // Call your function here!
      elm[0].innerHTML = scope.name;
    }
  }
})

请在此处查看完整示例:http://plnkr.co/edit/3SOWZrRHOldMRUEl7l0Z

注意:当需要进行DOM操作时,请始终使用指令!

编辑:要将整个对象传递给指令,请重写其scope对象:

scope: {
  block: '=data'
}

并在您的ng-repeat标记中:

<div ng-repeat="block in blocks" my-directive data="block"></div>

答案 1 :(得分:1)

你可以使用$ rootScope

[1]:https://docs.angularjs.org/api/ng/service/ $ rootScope“

[2]:http://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/

例如在JS中:

(function() {
  var global;

  global = (function() {
    function global($rootScope) {
      $rootScope.view_directory = "something";
    }

    return global;

  })();

  angular.module('yourapplication').run(['$rootScope', global]);

}).call(this);

例如在coffeescript(ngClassify)中:

class global extends Run
    constructor: ($rootScope) ->

        $rootScope.view_directory  = "something"

答案 2 :(得分:1)

回答我自己的问题。完整的工作代码段。根据接受的答案。

&#13;
&#13;
var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
  $scope.blocks = [
    {name: 'item #1'},
    {name: 'item #2'}
  ];
}).directive('externalBlock', function() {
  return {
    restrict: 'A',
    scope: {
      block: '=data'
    },
    link: function(scope, elm, attrs) {
      setupBlock(elm[0], scope.block);
    }
  }
});
&#13;
<script src="https://code.angularjs.org/1.4.0-rc.2/angular.js"></script>
<script>
  // this function is provided by external library
  // I want to setup each block in ng-repeat
  // it manipulated DOM
  function setupBlock(elm, block) {
    elm.innerHTML = block.name + ' [ready]';
  }
</script>

<body ng-controller="MainCtrl" ng-app="app">
  <div ng-repeat="block in blocks" external-block data="block"></div>
</body>
&#13;
&#13;
&#13;