javascript - angularjs无法在链接函数内分配作用域变量

标签 javascript angularjs angularjs-directive

嗨,我有以下代码片段。我的目标是允许创建多个 div,并将它们的位置、文本、高度和宽度绑定(bind)到 Controller 的模型。

appModule.controller('textController', function($scope){
    var box = {x: '0', y: '0', height: '100px', width: '200px', text: 'this is the default text'};

    $scope.textBoxes = [box];

    $scope.addNewTextBox = function(){
        console.log("creating new textbox!!!");
        $scope.textBoxes.push(box);
    };
});

appModule.directive('tbox', function($document){
    return {
        restrict: "E",
        template: '<div><div ng-transclude></div>',
        transclude: true, 
        scope: {
            model: "=",
        },
        link: function postLink(scope, element, attrs, ctrl){ //the scope here is the object's scope
            var length = scope.$parent.textBoxes.length;
            console.log(length);
            scope.model = scope.$parent.textBoxes[length-1];
        }
    }

});

我在这里遇到了一些问题。我无法将范围的模型变量分配给 Controller 中的 textBoxes 变量,说

Error: Non-assignable model expression: undefined (directive: tbox)
    at Error (<anonymous>)
    at h (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js:43:213)
    at Object.<anonymous> (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js:43:326)
    at Object.e.$digest (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js:87:13)
    at Object.e.$apply (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js:89:198)
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js:16:239
    at Object.d [as invoke] (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.

知道为什么吗?

最佳答案

由于错误报告“model”未定义,请尝试从指令的隔离范围中删除 model: "="

所以它看起来像这样:

scope: {},

关于javascript - angularjs无法在链接函数内分配作用域变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19346837/

相关文章:

angularjs - 单元测试 AngularJS 指令,该指令监视具有隔离范围的属性

javascript - 如何从 Array 的原型(prototype)函数返回数组对象?

javascript - 如何在 IonicFramework 中实现滑动手势?

javascript - 如何通过其偏移量查找 DOM 元素 ID/值

javascript - Angular : Pass $scope variable as directive attribute

javascript - 如何以 Angular 形式将地址或任何字段复制到另一个字段?

javascript - 使用JavaScript将多维对象数组转换为一维数组

javascript - 如何设置全日历 View 在当前日期前 1 周开始?

javascript - 手机锁定时 Socket.io 失去连接

javascript - 我想从 Controller 绑定(bind) iframe 的 src