我是Angularjs和Typescript的新手.
我会在这里尽量简短:
指令(directives / BikeDirective.ts):
class BikeDirective {
constructor() {
var directive: ng.IDirective = {};
directive.restrict = "E";
directive.scope = {
move: "="
};
directive.template = '<div>The bike</div>';
directive.link = (scope, element, attrs: any) => {
element.on('click', (e) => {
scope.move('moving!');
});
}
return directive;
}
}
export = BikeDirective;
控制器(controllers / MyController):
class MyController {
whatever: string;
constructor(public scope) {
this.whatever = "Whatever";
scope.vm = this;
}
onMove(msg: string) {
console.log(this.whatever);
}
}
export = MyController;
HTML:
<div ng-controller="myController">
<my-bike move="vm.onMove"></my-bike>
<my-bike move="vm.onMove"></my-bike>
</div>
应用程序
import MyController = require("controllers/MyController");
import BikeDirective = require("directives/BikeDirective");
class app {
constructor() {
var app = angular.module('app', [])
.controller('myController', ['$scope', MyController])
.directive('myBike', [BikeDirective]);
}
}
export = app;
主要
require.config({
baseUrl: '.',
paths: {
jquery: './Scripts/jquery-2.1.0',
angular: './Scripts/angular'
},
shim: {
'angular': {
exports: 'angular'
}
}
});
require(['app','angular','jquery'], (app, angular, $) => {
new app;
angular.bootstrap(document.body, ['app']);
});
我希望上面的代码可以自我解释.基本上,我想做的是单击其中一辆自行车(my-bike指令)时运行MyController.onMove()函数.一切正常.我唯一的问题是执行onMove时console.log(this.whatever)输出未定义,它不应该输出字符串“ whatever”吗?似乎MyController的范围在onMove()存根中不可用.
我在普通的Angularjs(没有TypeScript)中尝试过,它工作正常,是否缺少某些东西.
有人经历过吗?
我在此视频中遵循了BaSarat使用的.vm技术:http://www.youtube.com/watch?v=WdtVn_8K17E
谢谢
解决方法:
问题
问题出在move =“ vm.onMove”中,您正在将对函数的引用传递给指令,即
directive.scope = {
move: "="
};
onMove = (msg: string) => {
console.log(this.whatever); //OKAY
}
这进一步说明了这一点:https://www.youtube.com/watch?v=tvocUcbCupA&hd=1
更好的解决方法:
directive.scope = {
move: "&"
};
然后从您的html中调用它,即< my-bike move =“ vm.onMove()”>< / my-bike>.用vm调用函数.即vm.onMove()确保函数内部正确.
也与此问题无关
element.on回调在角上下文中不会被调用…因此您可能希望将回调包装在$scope.$apply中
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。