javascript - Angular directive attributes cause an error -
i trying write angular directive make substring of attribute passed in. below code:
html:
<body ng-controller="mainctrl"> <div><substring message="this test."></substring></div> <div><substring message="so this." ></substring></div> </body>
angular/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>' }; });
when try running following error:
html1300: navigation occurred. file: directive.html error: [$parse:syntax] syntax error: token 'is' unexpected token @ column 6 of expression [this test.] starting @ [is test.].
also, have tried changing
'=message' '@message'
but causes substring stuff doing in link function ignored.
why error? angular not seeing stuff in quotation marks string , instead trying parse out command? importantly, how fix this?
thanks
simply use @
text binding , rest of code works perfectly.
working example:
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 test."></substring> </div> <div> <substring message="so this."></substring> </div> </body> </html>
Comments
Post a Comment