组件绑定行为奇怪

时间:2017-01-28 17:07:24

标签: angularjs

我正在尝试学习如何使用组件绑定功能。 所以我写了一个组件:

'use strict';
var module = angular.module("Test", []);

module.controller("Controller2", Controller2);
module.component("compo2", {
    controller: "Controller2",
    bindings: {
        url: "@",
        thing: "<"
    }
});


Controller2.$inject = ["$scope"];
function Controller2($scope) {
    var self = this;
    this.$onInit = function () {
    }  
}

这是我的HTML:

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="./Test/angular.js"></script>
    <script src="./compoTest.js"></script>
</head>
<body ng-app="Test">
        <compo2 url="www.test.com" thing="a911"> T.E.S.T </compo2>
</body>
</html>

我读到了“@”和“&lt;”用于单向绑定。 “@”绑定工作正常,但“&lt;”绑定不会绑定字符串(如“a911”) 如果我尝试将'thing'属性设置为“911a”,它实际上会抛出一个错误,因为它不是一个数字。

我做错了什么或是预期的行为?

1 个答案:

答案 0 :(得分:0)

如果您想使用<单向绑定,可以

在compo2组件所在的控制器中,将字符串分配给this.myString = "a911"

等变量

controllerAs = "vm"语法:

<compo2 url="www.test.com" thing="vm.myString"> T.E.S.T </compo2>