簡體   English   中英

角度指令屬性導致錯誤

[英]Angular directive attributes cause an error

我正在嘗試編寫一個角度指令,以使傳入的屬性的子字符串成為可能。下面是我的代碼:

HTML:

<body ng-controller="MainCtrl">
     <div><substring message="This is a test."></substring></div>
     <div><substring message="So is this." ></substring></div>
</body>

角/ JavaScript的:

var app = angular.module('myapp', []);

app.controller('MainCtrl', function($scope) {

});

app.directive('substring', function () {
return {
    restrict: 'AE',
    replace: true,
    scope: { text: '=message' }, 
    link: function (scope, elem, attrs) {
        //alert(attrs.message); 
        var str = attrs.message;

        scope.text = str.substring(1, 4);
    },
    template: '<H1>{{text}}</H1>'
};
});

當我嘗試運行此命令時,出現以下錯誤:

HTML1300:發生導航。 文件:directive.html錯誤:[$ parse:syntax]語法錯誤:令牌'is'是表達式[這是一個測試。]的第6列中的意外令牌,從[是測試。]開始。

另外,我嘗試改變

'=message' to '@message'

但這只會導致我在鏈接函數中執行的子字符串操作被忽略。

為什么會出錯? Angular是否沒有將引號中的內容視為字符串,而是嘗試解析某些命令? 最重要的是,我該如何解決?

謝謝

只需使用@進行文本綁定,其余代碼即可完美運行。

工作示例:

 var app = angular.module('myapp', []); app.controller('MainCtrl', function($scope) { }); app.directive('substring', function() { return { restrict: 'AE', replace: true, scope: { message: '@' }, link: function(scope, elem, attrs) { //alert(attrs.message); var str = attrs.message; scope.text = str.substring(1, 4); }, template: '<H1>{{text}}</H1>' }; }); 
 <!DOCTYPE html> <html ng-app="myapp"> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body ng-controller="MainCtrl"> <div> <substring message="This is a test."></substring> </div> <div> <substring message="So is this."></substring> </div> </body> </html> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM