2017-02-24 81 views
2

我訪問範圍,像這樣:如何添加屬性到ng.Iscope?

let element = angular.element(document.getElementsByClassName('active')); 
    let scope = element.scope(); 

而我的範圍對象是這樣的,當我做一個

console.log(scope); 

$id:2017 $parent:ChildScope $root:Scope __private__:Object index:0 match:Object __proto__:Object

然而,當我嘗試這樣做:

console.log(scope.match); 

Typescript給出了語法錯誤:

(27,34): error TS2339: Property 'match' does not exist on type 'IScope'.

並打印出範圍。$ ID的工作

console.log(scope.$id); 

我知道這事做的$ id的文檔被定義,這樣的作品。 http://definitelytyped.org/docs/angularjs--angular-route/interfaces/ng.iscope.html

如何在不發生Typescript錯誤的情況下打印出我的成員變量scope.match?我想我需要擴展ng.IScope?

+0

這聽起來像屬性'match'不是在控制檯日誌的時間加入到範圍。你可以添加一個最小的工作例子嗎? – digijap

+0

是否可以檢查範圍屬性? 'if(scope.match == null)'由於錯誤TS2339而不起作用。 – fqlx

+0

你總是可以使用'if(angular.isUndefined(scope.match))',但是你應該真的弄清楚爲什麼你在嘗試訪問一個屬性時,它還沒有。 – digijap

回答

1

我能夠通過導出一個接口然後鑄造ng.IScope來解決這個問題。

請務必使用使其成爲可選參數。這就是我錯在哪裏

export interface IMyScope extends ng.IScope { 
    match?: any; 
} 

然後:

let myScope = <IMyScope>element.scope();