1

我有类似这样的标记角指令controlleras和纽带

<i class="fa-font icon-user" wd-user-profile></i> 

显示/隐藏这个div

<div id="user-profile" ng-show="vm.isVisible"> 
    <h3>user name</h3> 
    <h3>user email</h3> 
    <pre>{{vm | json:3}}</pre><!-- not updating on click --> 
</div> 

和指导这样的代码

angular 
    .module('myApp') 
    .directive('wdUserProfile', wdUserProfile); 

function wdUserProfile() { 
    var ddo = { 
    restrict: 'A', 
    templateUrl: 'app/components/_shared/_userProfile.html', 
    controller: UserProfileController, 
    controllerAs: 'vm', 
    bindToController: true, 
    link: function(scope, elem, attr, ctrl) { 
     elem.bind('click', scope.vm.onIconClick); 
     //elem.bind('click', ctrl.onIconClick); also doesn't work 
    } 
    }; 

    return ddo; 
} 

function UserProfileController() { 
    var vm = this; 

    vm.onIconClick = function() { 
    vm.isVisible = !vm.isVisible; 
    console.log(vm.isVisible); 
    }; 
} 

的问题是,虽然事件火灾和vm.isVisible变化很好,鉴于div没有任何反应。有什么想法吗?

回答

3

在角上下文外部运行的任何内容都不会包含角度摘要系统来运行摘要循环以更新绑定。

您需要手动启动摘要循环,因为您正在从事件(外部世界)更新范围。所以这将更新视图绑定。您可以使用scope.$apply()/$timeout运行摘要循环。

elem.bind('click', function(){ 
    //don't forget to inject $timeout depenency. 
    $timeout(scope.vm.onIconClick); //$timeout will run code in next digest 
})); 

当两个摘要周期发生冲突时可能会出现这种情况。只是你不能同时运行两个摘要循环。这里$ timeout的作用是如果假设一个摘要循环正在运行,并且您尝试使用$ timeout运行其他摘要循环,它会将新的摘要循环放入一个单独的队列中,直到第一个完成,然后评估排队的摘要循环,一次运行摘要循环完成。

+0

它不工作,所有的控制台是红色的(错误:$ rootScope:inprog 行动已在进行中) –

+1

@ georgiy.zhuravlev它应该工作..虽然尝试更新.. –

+0

适用()导致错误,但$超时版本的作品很棒,谢谢! –