错误:[$ compile:nonassign]与指令'myFacebook'一起使用的表达式'undefined'是不可分配的

问题描述 投票:46回答:6

我正在用angularjs编写指令,并遇到上述错误。我正在使用一本书中的代码。

.directive('myFacebook', [function(){
return {
    link: function(scope,element,attributes) {
        (function(d) {
                var js, id = 'facebook-jssdk',
                    ref = d.getElementsByTagName('script')[0];
                if (d.getElementById(id)) {
                    return;

                }
                js = d.createElement('script');
                js.id = id;
                js.async = true;
                js.src = "//connect.facebook.net/en_US/all.js";
                ref.parentNode.insertBefore(js, ref);
            }(document));
            // Initialize FB
            window.fbAsyncInit = function() {
                FB.init({

                    appId: 'xxxx', //birthday reminder
                    status: true, // check login status
                    cookie: true, // enable cookies to access the session
                    xfbml: false // parse XFBML
                });
                //Check FB Status
                FB.getLoginStatus(function(response) {
                     xxxx
                });
            };
        scope.username='';
    },
    scope: {
            permissions: '@',
            myFriends: '=friends'
        },
    controller: function($scope) {
        $scope.loadFriends = function() {
            FB.api('/me/friends?fields=birthday,name,picture', function(response) {
                    $scope.$apply(function() {
                        $scope.myFriends = response.data;
                    });
                });
        }
    },

    template:'Welcome {{username}}'
   }}])

我在]遇到错误>

 $scope.$apply(function() {
            $scope.myFriends = response.data;
 });

HTML代码

<div my-facebook></div>
<h1> My Friend's Birthday Reminder</h1>
<div ng-repeat="friend in myFriends">
     {{friend.name}}
</div>

我正在用angularjs编写指令,并遇到上述错误。我正在使用一本书中的代码。 .directive('myFacebook',[function(){return {link:function(scope,element,attributes){...

javascript angularjs angularjs-directive
6个回答
71
投票

问题是您没有在指令元素friends中定义属性<div my-facebook></div>


76
投票

我的解决方案在这里很难找到,但是更容易实现。我不得不将其更改为equivalent of(请注意,问号使该属性成为可选属性。在1.5之前,这显然不是必需的。)

scope: {
    permissions: '@',
    myFriends: '=?friends'
}


18
投票

[不是操作人员问题的直接答案,但这只是发生在我身上,所以对于将来可能会使用此错误的其他任何人,这类似于JohnP的答案。

如果您的指令中包含camelCase属性,也会出现此错误。

因此,如果您有:


4
投票

我遇到了同样的问题,对我来说,问题是DOM名称中的大写字符。

<div my-facebook FRIENDS="friendList"></div>

没有用,但是


0
投票

我有这个原因是因为我试图更新指令范围内的另一个变量,但是即使它是经过计算的,也不应该在html中传递,也不应该在html中传递

这是指令范围的示例

scope: {
  var1: '=',
  var2: '='
}

0
投票

如果您将其用作单向绑定,请适当地定义范围:

scope: {
   example: '<'
}

在我的情况下,我使用双向绑定作为单向绑定,传递了像这样的内联对象:

© www.soinside.com 2019 - 2024. All rights reserved.