【发布时间】: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