6

Tôi đang cố gắng đặt biến, selected.child, trên $scope để tôi có thể sử dụng nó ở nơi khác. Tôi vẫn còn mới với phạm vi trong Angular, nhưng không chắc chắn lý do tại sao tôi không thể thiết lập một cái gì đó trên phạm vi từ trong chỉ thị. Tôi có thể gọi chức năng phạm vi.AngularJS - Đặt một biến trên phạm vi từ chỉ thị

Tôi có JSfiddle cho mã và mã được đăng bên dưới.

Cảm ơn bạn đã trợ giúp trước.

HTML:

<div ng-controller="DashCtrl"> 
    <h3>{{selected.child}}<h3> 

    <div ng-repeat="child in children" select={{child}}> 
     {{child.username}} 
    </div> 
</div> 

Các javascript:

var dash = angular.module('dash', []); 

dash.directive('select', function() { 
    return { 
    restrict: "A", 
    scope: false, 
    link: function (scope, element, attrs) { 
     element.bind('click', function() { 
     scope.selected.child = jQuery.parseJSON(attrs.select); //Neither this 
     scope.setSelected(jQuery.parseJSON(attrs.select)); //Nor this is working 

      if (attrs.select != scope.selected) { 
      other_elements = angular.element(document.querySelectorAll('[select]')); 
       for (var i = 0; i < other_elements.length; i++) { 
        elm = jQuery(other_elements[i]); 
        elm.css('background', 'none'); 
       } 
       element.css('background', '#F3E2A9'); 
      } 
     }); 
    } 
    }; 
}); 

dash.controller('DashCtrl', function ($scope) { 
    $scope.setSelected = function (child) { 
    $scope.selected.child = child; 
    }; 

    $scope.children = [{ 
    "age_group": "6-8", 
     "username": "my_child" 
    }, { 
    "age_group": "8-10", 
     "username": "another_child" 
    }]; 

    $scope.selected = { 
    child: "none" 
    }; 


}); 

Trả lời

11

Bạn đang thiếu một cuộc gọi đến $ áp dụng Chỉ việc điều chỉnh mã của bạn như sau

  scope.selected.child = jQuery.parseJSON(attrs.select); //Neither this 
      // scope.setSelected(jQuery.parseJSON(attrs.select)); //Nor this is working 
scope.$apply(); 
Các vấn đề liên quan