【发布时间】:2015-03-17 19:40:55
【问题描述】:
我有一个 $scope 属性被传递到一个指令中,该指令正确绑定到父控制器。控制器中的 $scope 值正在通过控制器中的函数进行更新,但新值并未反映在指令中。
指令html:
<edit-item new-item="newItem" is-spanish="isSpanish" api="api" save-item="saveItem"></edit-item>
指令:
app.directive('editItem', function($rootScope){
return{
templateUrl: "../templates/edititem.html",
restrict: "E",
scope: {
api: '=',
newItem: '=',
saveItem: '=',
isSpanish: '='
},
controller: function($location, $scope){
var isPartner = $location.$$path.contains("partner");
var isOverview = $location.$$path.contains("overview");
var isService = $location.$$path.contains("service");
var isBlog = $location.$$path.contains("blog");
if(isPartner){
$scope.isPartner = true || false;
}
if(isOverview){
$scope.isOverview = true || false;
console.log($scope.isOverview);
}
if(isService){
$scope.isService = true || false;
}
if(isBlog){
$scope.isBlog = true || false;
}
}
}
});
模板:
<div class="editable">
<div class="editingTitle">
<a editable-text="newItem.title" ng-model="newItem.title">
<h4>{{ newItem.title || ' ' }}</h4>
</a>
<input ng-if="!isOverview" ng-model="newItem.shortname">
</div>
<div></div>
<div ng-switch on="isSpanish">
{{newItem}}
<div ng-switch-when="false" class="editingText" text-angular ng-model="newItem.contents"></div>
<div ng-switch-when="true" class="editingText" text-angular ng-model="newItem.contentsSp"></div>
<a class="editApply" ng-click="saveItem(newItem, api)">Apply Revisions</a>
</div>
</div>
父控制器:
$rootScope.newItem = {};
newItem 一开始是空的。编辑项目时,当前选择的项目被传递到 newItem。
那是通过兄弟指令:
<div class="editList">
<div class="editWrapper" ng-repeat="item in list">
<div class="editTitle"><a href="">{{item.title}}</a></div>
<a ng-click="editItem(item)"><div class="editEdit">Edit</div></a>
<a ng-click="deleteItem(item, api)" ><div class="editDelete"> Remove</div></a>
{{newItem}}
</div>
editItem(Item);函数只是将点击的项目设置为新项目:
$scope.editItem = function(item){
$scope.newItem = item;
}
当一个 promise 被解决时,我正在切换 newItem 的内容......发生了一些逻辑,循环通过另一个服务中的项目,匹配一个与其属性匹配的项目并返回该项目。这一切正常。这是控制器上的解析方法,它将检索到的项目设置为新项目:
function getSpanishOverviewByIDSuccess(data) {
$rootScope.newItem = data;
console.log(data);
}
newItem 是在父控制器中更新的值。登录到控制台时,我可以看到值正在更新,但指令中没有。
我有什么遗漏的吗?我相信 '=' 应该执行双向绑定。
【问题讨论】:
-
我们可以看看
edititem.html,以及你正在改变的控制器newItem吗?通常,当值的修改在摘要之外完成时,就会发生这种情况。$scope.$apply()通常可以解决问题。 -
你是通过javascript还是angular调用这个函数?如果是 javascript,则需要包含 $rootScope.$apply()。
-
它是通过角度
-
我有点困惑......你有 ng-click="saveItem(newItem, api)",你也有 saveItem: '=' 在你的指令范围和 save-item=指令 HTML 中的“saveItem”。您是否期望 ng-click 会在您的指令中调用 saveItem ?还是在您的控制器中声明了不同的 saveItem?
-
我添加了更多信息,显示了添加和更新新项目的过程。
标签: angularjs angular-directive