Search code examples
javascriptangularjsyeomanyeoman-generator-angular

AngularJS directive scope seems to accept only one argument


i started learning AngularJS and i got stuck on creating my own costume directive.

So, first of all, i'm using yeoman project to generate an AngularJS project and this is my starting point.

Now, to the subject -

I have the following code:

app.js:

myapp.directive('userinfo', function() {
        var directive = {};

        directive.restrict = 'E';
        directive.template = '<b>User: {{ user.firstName }} {{ user.lastName}}</b>';

        directive.scope = {
            user : '='/*, editing: false*/
        };

        return directive;
    });

index.html:

<body ng-app="proj2App" ng-controller="MainCtrl">
...
<userinfo user="users[0]"> </userinfo>
...
</body>

main.js:

angular.module('proj2App')
  .controller('MainCtrl', function ($scope) {
    $scope.users = [
        { firstName : 'John', lastName: 'Doe'}
                     ];
  });

My problem as it seems, is found at app.js in the line where i'm defining directive.scope. Whenever it is like that:

        directive.scope = {
            user : '='/*, editing: false*/
        };

There is no problem and everything works just fine.. But then, when i remove the comment block and it looks like that:

        directive.scope = {
            user : '=', editing: false
        };

It doesn't work - the page won't show the template and angular will throw the following error which to me absolutely says nothing:

**TypeError**: undefined is not a function
    at http://localhost:9000/bower_components/angular/angular.js:6436:30
    at forEach (http://localhost:9000/bower_components/angular/angular.js:331:20)
    at parseIsolateBindings (http://localhost:9000/bower_components/angular/angular.js:6435:5)
    at http://localhost:9000/bower_components/angular/angular.js:6494:49
    at forEach (http://localhost:9000/bower_components/angular/angular.js:323:20)
    at Object.<anonymous> (http://localhost:9000/bower_components/angular/angular.js:6480:13)
    at Object.invoke (http://localhost:9000/bower_components/angular/angular.js:4182:17)
    at Object.enforcedReturnValue [as $get] (http://localhost:9000/bower_components/angular/angular.js:4035:37)
    at Object.invoke (http://localhost:9000/bower_components/angular/angular.js:4182:17)
    at http://localhost:9000/bower_components/angular/angular.js:4000:37

Does someone know what is happening here?


Solution

  • Set the editing variable in the link function

    myapp.directive('userinfo', function () {
        var directive = {};
    
        directive.restrict = 'E';
        directive.template = '<b>User: {{ user.firstName }} {{ user.lastName}}</b>';
    
        directive.scope = {
            user: '='
        };
    
        directive.link = function (scope) {
            scope.editing = false;
        };
    
        return directive;
    });