2016-07-15 109 views
1

我試圖寫一個角度指令,使傳遞進來的屬性的子下面是我的代碼:角指令屬性導致錯誤

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: Navigation occurred. File: directive.html Error: [$parse:syntax] Syntax Error: Token 'is' is an unexpected token at column 6 of the expression [This is a test.] starting at [is a test.].

而且,我試圖改變

'=message' to '@message' 

但只是使子的東西,我在鏈接功能做給被忽略。

爲什麼錯誤? Angular沒有看到引號中的東西是字符串,而是試圖解析出一些命令?最重要的是,我該如何解決這個問題?

感謝

+0

請把錯誤。或者,如果有可能在jsfiddle或任何其他類似的工具上重現錯誤 – jcvegan

+0

@jcvegan - 我一直試圖發佈錯誤,但Stackoverflow阻止我的問題,說錯誤是格式不正確的代碼。你知道在這附近嗎? – Dave

+0

你有沒有嘗試把你的消息放在單引號中? 'message =「'這就是這個。'」' – tymeJV

回答

2

只需使用@文本結合,你的代碼的其餘部分完美的作品。

工作例如:

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>

+0

感謝您的幫助。你能說明在指令中使用它們時,'@'和'='之間的區別嗎?我仍然對什麼時候應該使用其中一個有困惑。 – Dave