【问题标题】:How to update a model of directive 1 from directive 2 and see changes on view?如何从指令 2 更新指令 1 的模型并查看视图更改?
【发布时间】: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


【解决方案1】:

根据 jsbin 中的代码,已经使用了 ng-template,如果是这种情况,那么您已经为模板提供了一个 id 或类,如下 id="myTpl",并使用 ng-include 指令包含它

  <script type="text/ng-template" id="myTpl">
    <div class="box linkbox" >
      <div class="inr">
        <div class="content">
            <h3 class="title" ng-bind="lbCtrl.boxTitle"></h3>
            <ul>
                <li><a>link 1</a></li>
                <li><a>link 2</a></li>
            </ul>
        </div>
      </div>
    </div>    
</script>


<div link-box sub-categories  ng-include="'myTpl'"></div>

http://jsbin.com/baneyezezu/1/edit?html,js,output

【讨论】:

    猜你喜欢
    • 2020-03-03
    • 1970-01-01
    • 2016-08-13
    • 1970-01-01
    • 2014-12-09
    • 2014-07-22
    • 1970-01-01
    • 2017-07-22
    • 2014-08-23
    相关资源
    最近更新 更多