在scopecript属性

时间:2015-05-21 21:54:04

标签: javascript angularjs typescript undefined

我正在尝试将范围用作控制器的属性,但是当我在程序中使用它时,它抛出了一个未定义的异常。有没有办法解决这个问题,或者在类中使用$ Scope的更好方法?

class PositionCtrl {

    $scope : ng.IScope;
    MyMap: google.maps.Map;
    //rectangles: Rectangle[];
    lat: number; long: number; rad: number;
    save() {
        alert("Settings Saved");
    }

    constructor() {            
        this.lat = 20;
        this.long = 20;
        this.rad = 10000;

        var mapCanvas = document.getElementById('map-canvas');
        var mapOptions = {
            center: new google.maps.LatLng(Number(this.lat), Number(this.long)),
            zoom: 8,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            disableDoubleClickZoom: true
        }
        this.MyMap = new google.maps.Map(mapCanvas, mapOptions)

        var marker = new google.maps.Marker({
            map: this.MyMap,
            position: new google.maps.LatLng(Number(this.lat), Number(this.long)),
            title: 'Some location'
        });

        var circle = new google.maps.Circle({
            map: this.MyMap,
            
            radius: Number(this.rad),
            fillColor: '#AA0000',
            clickable: false
        });
        
        circle.bindTo('center', marker, 'position');        

        //WATCH IS UNDEFINED
        this.$scope.$watch('Pos.rad', () => {
            circle.setRadius(Number(this.rad));
            circle.bindTo('center', marker, 'position');
            console.log("done");
        });
        //WATCHGROUP IS UNDEFINED
        this.$scope.$watchGroup(['Pos.lat', 'Pos.long'],() => {
            marker.setPosition(new google.maps.LatLng(Number(this.lat), Number(this.long)));

            console.log("done");
        });
            
        //Click event
        google.maps.event.addListener(this.MyMap, 'click',(event) => {
            marker.setPosition(event.latLng);
            this.$scope.$apply(() => {
                this.lat = event.latLng.lat();
                this.long = event.latLng.lng();
            })
            var test: number = 0;
            console.log(this.lat);
            test = Number(this.rad);
            circle.setRadius(test);
            console.log(this.rad);
            console.log(circle.getRadius());
            circle.bindTo('center', marker, 'position');
        });
    }
    event: google.maps.event;           
}

var myApp = angular.module('myApp', []);
myApp.controller("PositionCtrl", ["$scope", PositionCtrl]);

1 个答案:

答案 0 :(得分:1)

Angular无法知道您有$scope成员。

您需要为其添加构造函数参数:

 class MyClass {
    constructor(public $scope: ng.IScope) {
        // OK to use this.$scope here 
    }
 }

您还可以使用$inject

class MyClass {
    // Parallel array to constructor arguments
    static $inject = ['$scope'];
    constructor(public myScope: ng.IScope) {
        myScope.$watch(...);
    }
}