AngularJS指令范围似乎只接受一个参数

AngularJS directive scope seems to accept only one argument

本文关键字:参数 一个 范围 指令 AngularJS      更新时间:2023-09-26

我开始学习AngularJS,但我坚持创建自己的服装指令。

所以,首先,我使用yeoman项目来生成一个AngularJS项目,这是我的起点。

现在,进入主题——

我有以下代码:

应用.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;
    });

索引.html

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

主.js

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

的问题似乎在app.js我定义指令.scope的行中找到。每当是这样的时候:

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

没有问题,一切都很好。但是,当我删除评论块时,它看起来像这样:

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

它不起作用 - 页面不会显示模板,并且角度会抛出以下错误,对我来说绝对什么也没说:

**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

有人知道这里发生了什么吗?

link函数中设置editing变量

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;
});