我想轉換作用域變量,如修剪傳遞的字符串。 但它始終顯示它通過。Angular 1.x指令範圍
這裏是我的示例代碼,
export function testDirective() {
return {
restrict: 'E',
template: `<a>{{vm.testText}}</a>`,
scope: {
testText: '@'
},
controller: TestController,
controllerAs: 'vm',
bindToController: true
}
}
export class TestController {
testText: string;
constructor(private $scope: angular.IScope) {
// when getting variable, I need to transform the value
$scope.$watch(() => this.testText, (newVal: string) => {
this.testText = newVal.trim() + ' Edited'; // this doesn't affact
});
}
}
爲什麼代碼不能正常工作?
爲了使它工作,我增加了額外的變量(trimmedText),但我不認爲這是正確的做法,
export function testDirective() {
return {
restrict: 'E',
template: `<a>{{vm.trimmedText}}</a>`,
scope: {
testText: '@'
},
controller: TestController,
controllerAs: 'vm',
bindToController: true
}
}
export class TestController {
testText: string;
trimmedText: string;
constructor(private $scope: angular.IScope) {
// when getting variable, I need to transform the value
$scope.$watch(() => this.testText, (newVal: string) => {
this.trimmedText = newVal.trim() + ' Edited'; // it works
});
}
}
請諮詢我
@Expert想成爲,看起來您正在使用Angular 2與ES2015/ES6一起使用的現代基於組件的架構,我將嘗試在Angular中使用Angular 2模式今天1,幷包括一個例如在我的答案中使用Angular 2模式,因爲這個課程對於週末是免費的https://egghead.io/courses/using-angular-2-patterns-in-angular-1-x-apps :) –
謝謝你的回答和評論,所以要使用'=',我應該傳遞一個對象,而不是一個字符串! –