2016-09-06 230 views
0

我想轉換作用域變量,如修剪傳遞的字符串。 但它始終顯示它通過。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 
     }); 
    } 
} 

請諮詢我

回答

1

@Expert想成爲,使用=登錄的指令定義的隔離範圍在指令內設置雙向數據綁定。

檢查下面的代碼片段,here's的的jsfiddle link.You可以找到不同類型的數據的指令here

的HTML

<div ng-app="demo"> 
    <div ng-controller="DefaultController as ctrl"> 
    <custom-directive test-text="ctrl.text"></custom-directive> 
    </div> 
</div> 

的角碼

angular 
    .module('demo', []) 
    .controller('DefaultController', DefaultController) 
    .controller('CustomDirectiveController', CustomDirectiveController) 
    .directive('customDirective', customDirective); 

    function DefaultController() { 
    var vm = this; 
    vm.text = 'Hello, '; 
    } 

    function customDirective() { 
    var directive = { 
     restrict: 'E', 
     template: `<a href="#">{{vm.testText}}</a>`, 
     scope: { 
     testText: '=' 
     }, 
     controller: CustomDirectiveController, 
     controllerAs: 'vm', 
     bindToController: true 
    }; 

    return directive; 
    } 

    function CustomDirectiveController() { 
    var vm = this; 
    // transforming/updating the value here 
    vm.testText = vm.testText + 'World!'; 
    } 
綁定的詳細信息
+0

@Expert想成爲,看起來您正在使用Angular 2與ES2015/ES6一起使用的現代基於組件的架構,我將嘗試在Angular中使用Angular 2模式今天1,幷包括一個例如在我的答案中使用Angular 2模式,因爲這個課程對於週末是免費的https://egghead.io/courses/using-angular-2-patterns-in-angular-1-x-apps :) –

+0

謝謝你的回答和評論,所以要使用'=',我應該傳遞一個對象,而不是一個字符串! –

0
$scope.$watch(() => this.testText, // <-- use this.textText here 
+0

對不起,這是mistypo錯誤;(不更新視圖 –

0

'@' 是不正確的綁定,如果你想修改它 - 使用'='。 但使用附加變量實際上是正確的方法。

簡單轉換的另一個好方法是使用過濾器。

+0

如果我改變爲'=',我得到這個錯誤,詞法錯誤:未知d nextharacter在列0-0 ... –