【问题标题】:scope.$eval doesn't work in angular.js directivescope.$eval 在 angular.js 指令中不起作用
【发布时间】:2014-09-20 14:52:44
【问题描述】:

我想构建一个 angular.js 指令,通过单击 <span>,它将变成可编辑的输入。并且下面的代码运行良好,除非模型为空或模型长度为0,使其显示<span> EMPTY </span>

  <span  ng-editable="updateAccountProfile({'location':profile.location})" ng-editable-model="profile.location"></span> 

app.directive('ngEditable', function() {
    return {
        template: '<span class="editable-wrapper">' + '<span data-ng-hide="edit" data-ng-click="edit=true;value=model;">{{model}}</span>' + '<input type="text" data-ng-model="value" data-ng-blur="edit = false; model = value" data-ng-show="edit" data-ng-enter="model=value;edit=false;"/>' + '</span>',
        scope: {
            model: '=ngEditableModel',
            update: '&ngEditable'
        },
        replace: true,
        link: function(scope, element, attrs) { 

           var value = scope.$eval(attrs.ngEditableModel);
           console.log('value ' , attrs.ngEditableModel , value);
           if (value == undefined || (value != undefined && value.length == 0)) {
             console.log('none');
             var placeHolder = $("<span>");
             placeHolder.html("None");
             placeHolder.addClass("label");
             $(element).attr("title", "Empty value. Click to edit.");
           }


            scope.focus = function() {
                element.find("input").focus();
            };
            scope.$watch('edit', function(isEditable) {
                if (isEditable === false) {
                    scope.update();
                } else {
                    // scope.focus();
                }
            });
        }
    };
});

问题发生在这部分代码

    var value = scope.$eval(attrs.ngEditableModel);
    console.log('value ' , attrs.ngEditableModel , value);

attrs.ngEditableModel 输出内容 'profile.location',但随后使用 scope.$eval() 只输出 'undefined',甚至模型 'profile.location' 也不为空

【问题讨论】:

  • 请使用代码 sn-p 以便我们可以看到您的代码的工作版本。(进入编辑模式,然后您可以使用 Ctrl + M)
  • 为什么要在一个属性上使用scope.$eval,而该属性已经将其值分配给了作用域的model 变量?

标签: angularjs angularjs-directive


【解决方案1】:

你有两种方法可以解决这个问题。

1) 您在错误的范围内调用 $eval。您在链接功能中有scope 新创建的隔离范围。 attrs.ngEditableModel 确实包含对指令外部范围的引用,这意味着您必须在 scope.$parent 处调用 $eval。

scope.$parent.$eval(attrs.ngEditableModel)

或 2) 更好的处理方式:您已经通过范围定义绑定了 ngEditableModel

scope: {
    model: '=ngEditableModel',

因此,您可以使用指向attrs.ngEditableModel 值的scope.model,而不是使用您自己的$eval 调用。这已经是双向绑定了。

【讨论】:

  • 奇怪的是,当console.log(scope) 时,我可以在控制台中看到scope.model 的值,但是当console.log(scope.model) 时,输出未定义。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-31
  • 1970-01-01
  • 2014-11-03
  • 1970-01-01
  • 2013-02-26
  • 2014-07-09
  • 2013-08-28
相关资源
最近更新 更多