简体   繁体   中英

AngularJS: Communication between directives and view updation

I am new in AngularJS. I search throw a lot of information and find some nice solution that should work for me ( AngularJS communication between directives ). Code in first directive looks like that:

angular.module('app')
  .directive('myItem', function () {
    return {
      templateUrl: 'views/item.html',
      restrict: 'C',
      controller: function ($scope, $element) {
        $element.closest('.models-slider').on('afterChange', function(event, slick, currentSlide){
          $scope.$emit('model:updated', currentSlide);
        });
      }
 })

And in second:

angular.module('app')
  .directive('model', function () {
    return {
      templateUrl: 'views/model.html',
      restrict: 'E',
      controller: function ($scope, $element) {
       $scope.$on('model:updated', function(e, data){
         $scope.item = data;
         console.log('scope',  $scope); // Here I see right value of item
       });
     });
    }
 });

But the problem is inside view/model.html:

<div class="left-block">
  <a class="back" href="#"></a>
  <div class="model-wrapper">
    <div class="front-view active">
      <img src="images/model.png"/>
      <img ng-if="item.frontImage" ng-src="{{ item.frontImage }}"/>
    </div>
    <a class="rotate"></a>
  </div>
</div>

It doesn't update. Is there are any mistakes in my code? How can I update my view?

因为afterChange是一个非角度事件,所以在myItem指令中在scope.$apply中发出' model:updated '

Your question is not quite clear though, I will try to give some answer or hints for you consider:

First, the $scope.$on is not intended for you to pass data between different scopes. And why do you want to use the restriction of C for your myItem directive? how are you using the two directives my-item and model ? where are they in your views?

You can build a bi-directional binding between directive and controller (or controller for another directive). You need to make an isolated scope in the directive myItem :

angular.module('app')
  .directive('myItem', function () {
    return {
      templateUrl: 'views/item.html',
      restrict: 'AEC',
      scope: {
          item: '='   //bi-directional binding
       },
      controller: function ($scope, $element) {
        $element.closest('.models-slider').on('afterChange', function(event, slick, currentSlide){
         // $scope.$emit('model:updated', currentSlide);
         $scope.item = currentSlide;
        });
      }
 })

In the directive template for your model , you can get the item

<my-item item="item"></my-item>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM