【发布时间】:2015-03-12 05:08:38
【问题描述】:
我想做一些我认为是使用“咖啡脚本类”和 Angular JS 结构的好方法。
<!doctype html>
<html ng-app>
<head>
<meta charset=utf-8>
<meta name=viewport content="width=device-width, initial-scale=1">
<title>Main Test</title>
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/angular.min.js"></script>
<script type="text/javascript" src="js/coffee.js"></script>
</head>
<body>
<div ng-controller="MainClass" style="margin-left:10px">
<h2>All todos: {{test()}}</h2>
</div>
</body>
</html>
请注意,我将 DIV ng-controller 设置为 MainClass 并在 H2 HTML 标记内绑定 test() 方法。
class AngularJSController
constructor: ($scope, $main) ->
$scope.test = MainClass.prototype.test
MainClass.test = MainClass.prototype.test
$main.test = MainClass.prototype.test
test = MainClass.prototype.test
@test = MainClass.prototype.test
console.log @test
class MainClass extends AngularJSController
constructor: ($scope) ->
super $scope, this
setTimeout (->
console.log test()
), 1000
test();
test: -> 'aloha!'
在 AngularJSController 构造函数中,我尝试了所有我想在 MainClass 范围内设置我的超类方法 TEST 的形式,但没有成功。
我正在尝试这样做,因为我只想在我的 Angular JS 控制器和组件上使用类。
我已经遇到的问题:
-
如果我尝试在 setTimeout 中使用
@test()而不是test(),jQuery 已经将this属性替换为一种 JQuery 窗口对象。setTimeout (-> console.log @test()), 1000 -
我不知道
test()的真正范围是什么,如果这个地方(或@cause Coffee)与地方任何东西都不一样。test() != this.test() != @.test() # the first scope isn't the same scope of last two calls
【问题讨论】:
-
您在示例中基本上需要的是一个服务,将可重用的方法附加到控制器,如果您希望该服务成为一个类 AngularJS 不在乎,但控制器应该始终是函数(按设计)。
-
加缪,我的想法更简单。我只想创建我的类,继承一个简单的基类,让我能够使用 Coffee Script Classes Structure 对我的组件进行编程。只是它!在不改变 Coffee 或 Angular 的任何一种实现方式的情况下,成为与 Coffee 和 Angular 一起使用的简单、有用且非常小的框架。你明白了吗?
-
有一个很好的解决方案:github.com/lucassus/mongo_browser/blob/…
-
@MarceloFilho 你能接受我的回答吗?
标签: class controller coffeescript angularjs