【问题标题】:AngularJS attr binding from parent to child component not working从父组件到子组件的AngularJS attr绑定不起作用
【发布时间】:2020-12-18 12:51:29
【问题描述】:

我在 AngularJS 中创建了一个简单的单模块应用程序。主体被包裹在一个控制器中,这个控制器从 jsonplaceholder(一个用户数组)中获取虚拟数据。我还创建了一个组件并将其附加到同一个控制器,名为 <my-comp> 并使用 attr 绑定我试图传递从 http 调用收到的对象数组,但是它会引发以下错误:

angular.js:15697 错误:[$parse:syntax] http://errors.angularjs.org/1.8.2/$parse/syntax?p0=%7B&p1=invalid%20key&p2=2&p3=%7B%7Busers%7D%7D&p4=%7Busers%7D%7D

你能帮我找出我犯错的地方吗? 我会留下一个(不)工作的 sn-p。

angular.module('mainApp', [])
    .controller("controlador", function($q, $http, $scope) {
        $scope.users = [];

        $http({
            method: 'GET',
            url: 'https://jsonplaceholder.typicode.com/users'
        }).then(function successCallback(response) {
            console.log('response', response.data)
            $scope.users = response.data;

        }, function errorCallback(response) {
            console.log('response', response)
        })
    })

.component("myComp", {
    bindings: { attr1: '=' },
    controllerAs: "modelo",
    template: '<p ng-repeat="user in attr1">{{user.name}}</p>'
})
<!DOCTYPE html>
<html ng-app="mainApp">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>components binding symbols</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.2/angular.min.js" integrity="sha512-7oYXeK0OxTFxndh0erL8FsjGvrl2VMDor6fVqzlLGfwOQQqTbYsGPv4ZZ15QHfSk80doyaM0ZJdvkyDcVO7KFA==" crossorigin="anonymous"></script>
</head>

<body ng-controller="controlador">

    <my-comp attr1="{{users}}"></my-comp>

    <script src="app.js"></script>
</body>

</html>

谢谢。

【问题讨论】:

  • 看起来您没有解析响应。在分配 response.data 之前,请执行 JSON.parse(response.data)

标签: angularjs


【解决方案1】:

{{...}} 表示计算其中的表达式。 要传递一个变量,例如在您的 2 路绑定 (attr1: '=') 的情况下,您只需要执行 attr1="users"

您使用该组件的 sn-p 将如下所示:

<body ng-controller="controlador">

    <my-comp attr1="users"></my-comp>

    <script src="app.js"></script>
</body>

【讨论】:

    猜你喜欢
    • 2016-11-18
    • 2017-05-02
    • 2018-03-16
    • 2017-11-12
    • 2021-09-12
    • 2018-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多