【发布时间】:2015-11-02 04:55:54
【问题描述】:
我有两个指令,我想在指令 1 中更新模型(this in controllerAs 语法)。
// Linkbox
SApp.directive('linkBox', ['$rootScope', '$compile', '$templateCache', '$state', '$timeout', function($rootScope, $compile, $templateCache, $state, $timeout){
return {
controller: function($scope, $element, $attrs, $transclude) {
var vm = this;
vm.setBoxTitle = function(title){
vm.boxTitle = title;
console.log('setBoxTitle', title); // returns correct value!
// also tried this:
// $timeout(function(){
// vm.boxTitle = title;
// console.log('title of box', vm.boxTitle);
// }, 1);
}
},
restrict: 'A',
templateUrl: 'linkbox.html',
controllerAs: 'lbCtrl',
link: function($scope, iElm, iAttrs, controller) {
console.log('link');
}
};
}]);
// SubCategories linkbox
SApp.directive('subCategories', ['$rootScope', '$compile', '$templateCache', '$state', function($rootScope, $compile, $templateCache, $state){
return {
require: 'linkBox',
restrict: 'A',
link: function($scope, iElm, iAttrs, lbCtrl) {
lbCtrl.setBoxTitle('Title of box...');
}
};
}]);
使用指令:
<div link-box sub-categories ></div>
这是视图 (linkbox.html)
<div class="linkbox">
<h3 class="title" ng-bind="lbCtrl.boxTitle"></h3>
<ul> <li> <a>...</a> </li> </ul>
</div>
指令的通信正常,console.log 返回正确的值,但我看不到视图有任何变化。你能帮忙吗?
更新:
当我在 linkBox 指令的链接函数中手动设置 controller.boxTitle = 'A title' 时,View 已经更新了值。所以html代码没有问题。
问题已解决。
link-box 指令的另一种用法是这样的:
<div link-box sub-categories ></div>
<div class="area" link-box related-searchs ></div>
在第二次使用链接框时,我只是添加了另一个指令而没有设置标题。我应该使用隔离范围来防止不同模块的模型之间发生冲突。
【问题讨论】:
-
你在更新值后尝试过 $scope.$apply 吗?
-
@ashfaq.p 刚刚测试过(
vm.boxTitle = title之后)。 => 错误:$digest 已经在进行中 -
那你可以试试$timeout。
-
@ashfaq.p 没用 :(
-
创建一个小提琴或 plunker,我会帮忙。
标签: angularjs angularjs-directive