在AngularJS框架中处理数据建模的方式解析(4)

module.service('myservice', function($http, $q) { // This breaks when minified }); to this: module.service('myservice', [ '$http', '$q', function($http, $q) { // Using the array syntax to declare dependencies works with minification<b>!</b> }]);

这个数组语法很好的解决了这个问题。我的建议是从现在开始照这个方法写,如果你决定压缩JavaScript,这个方法可以让你少走很多弯路。好像是一个automatic rewriter机制,我也不太清楚这里面是怎么工作的。

最终一点建议:如果你想用数组语法复写你的functions,在所有Angular依赖注入的地方应用之。包括directives,还有directive里的controllers。别忘了逗号(经验之谈)

// the directive itself needs array injection syntax: module.directive('directive-with-controller', ['myservice', function(myservice) { return { controller: ['$timeout', function($timeout) { // but this controller needs array injection syntax, too! }], link : function(scope, element, attrs, ctrl) { } } }]);

注意:link function不需要数组语法,因为他并没有真正的注入。这是被Angular直接调用的函数。Directive级别的依赖注入在link function里也是使用的。

 Directive永远不会‘完成'

在directive中,一个令人掉头发的事就是directive已经‘完成'但你永远不会知道。当把jQuery插件整合到directive里时,这个通知尤为重要。假设你想用ng-repeat把动态数据以jQuery datatable的形式显示出来。当所有的数据在页面中加载完成后,你只需要调用$(‘.mytable).dataTable()就可以了。 但是,臣妾做不到啊!

为啥呢?Angular的数据绑定是通过持续的digest循环实现的。基于此,Angular框架里根本没有一个时间是‘休息'的。 一个解决方法就是将jQuery dataTable的调用放在当前digest循环外,用timeout方法就可以做到。

angular.module('table',[]).directive('mytable', ['$timeout', function($timeout) { return { restrict : 'E', template: '<table>' + '<thead><tr><th>counting</th></tr></thead>' + '<tr ng-repeat="data in datas"><td></td></tr>' + '</table>', link : function(scope, element, attrs, ctrl) { scope.datas = ["one", "two", "three"] // Doesn't work, shows an empty table: // $('.mytable', element).dataTable() // But this does: $timeout(function() { $('.mytable', element).dataTable(); }, 0) } } }]);

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgyxgy.html