【问题标题】:Angular directive attributes cause an errorAngular 指令属性导致错误
【发布时间】:2016-11-19 01:43:20
【问题描述】:

我正在尝试编写一个角度指令来制作传入属性的子字符串。下面是我的代码:

HTML:

<body ng-controller="MainCtrl">
     <div><substring message="This is a test."></substring></div>
     <div><substring message="So is 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>'
};
});

当我尝试运行它时,我收到以下错误:

HTML1300:发生导航。 文件:directive.html 错误:[$parse:syntax] 语法错误:标记 'is' 是表达式 [This is a test.] 的第 6 列中的意外标记,从 [is a test.] 开始。

另外,我尝试过改变

'=message' to '@message'

但这只会导致我在链接函数中所做的子字符串被忽略。

为什么会出错? Angular 是否没有将引号中的内容视为字符串,而是试图解析出一些命令?最重要的是,我该如何解决这个问题?

谢谢

【问题讨论】:

  • 请输入错误。或者如果有可能在 jsfiddle 或任何其他类似工具上重现错误
  • @jcvegan - 我一直在尝试发布错误,但 Stackoverflow 阻止了我的问题,说错误是代码格式不正确。你知道吗?
  • 您是否尝试过将您的信息放在单引号中? message="'So is this.'"
  • @Dave 您正在使用attrs.message 访问文本。为什么需要定义新的范围?
  • @cem 我不确定你的意思。这是我第一次编写指令(对 Angular 来说还是新手)。我遵循的例子就是这样做的。我尝试删除自定义范围,但仅在两个位置都使用最后一个值时遇到了指令问题。你能详细说明一下你的意思吗?

标签: javascript angularjs


【解决方案1】:

只需使用@ 进行文本绑定,其余代码即可完美运行。

工作示例:

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>

【讨论】:

  • 感谢您的帮助。你能解释一下在指令中使用'@'和'='的区别吗?我仍然对何时应该使用其中一种感到困惑。
猜你喜欢
  • 1970-01-01
  • 2019-02-21
  • 1970-01-01
  • 2016-07-29
  • 1970-01-01
  • 1970-01-01
  • 2018-09-28
  • 2020-04-06
  • 1970-01-01
相关资源
最近更新 更多