1

올바른 개체에 적합한 속성을 설정하는 방법을 알고 싶습니다. Select2 "change"핸들러에서 각도 범위에 액세스하는 방법은 무엇입니까?

enter image description here

는 현재 "변경"이벤트 처리기에서 나는에있어 범위에 대한 지식이 없습니다. 효과적으로 내가 업데이트해야하는 위치를 알 수 없습니다.

Plunker : http://plnkr.co/edit/T4aBzND7VV2gCkui0I7P?p=preview

코드가 강조

app.controller('MyCtrl', ['$scope', function ($scope) { 
    $scope.locations = ['Paris', 'London']; 
}]); 

app.directive('timezone', function(timezones) { 
    var _updateSetting = function(e) { 
     console.log(e.target.value); 
     // How do I update objects in my scope? 
     // (cannot access here) 
    }; 
    return { 
     restrict: 'E', 

     link: function(scope, el, attrs) { 
      el.select2({ data: timezones.get() }).on("change", _updateSetting); 
     }, 

     template : "<input type='hidden' class='timezoneSelector' style='width: 100%;'>" 
    } 
}); 

app.factory('timezones', function() { 
    var timezones = ["Europe/London", "Europe/Paris"]; 
    var timezonesSelect = timezones.map(function(obj) { return {id: obj, text: obj }; }); 
    // preparing data so it is ready to use for select2 
    return { 
     get : function() { return timezonesSelect; } 
    } 
}); 

참고 : 나는 제어 :

될, 내 코드에 더 가까이 있고 싶어 https://github.com/angular-ui/ui-select2 사용하지 않으

참고 : Select2는 일부 오프 스크린 div를 구성하며 잠재적으로는 $(e.target).parent().text()을 그냥 나에게 예쁘게

제대로 "각도의 방법"에서이 작업을 수행하는 방법을 어떤 제안이 있다면

- 이것은 나의 마음에 드는 경우 나 답변/의견 :

답변

3

당신은 @urban_racoons '대답으로 매개 변수로 전달하여 범위를 액세스 할 수 있습니다. 그러나 Angular 외부의 이벤트를 사용할 때 $apply을 사용하여 범위를 업데이트했다는 사실을 알려야합니다.

app.directive('timezone', function(timezones) { 
     var _updateSetting = function(scope, e) { 
      console.log(e.target.value); 
      // now you can update scope 
     }; 

     return { 
      restrict: 'E', 

      link: function(scope, el, attrs) { 
       el.select2({ data: timezones.get() }).on("change", function(e) { 
        scope.$apply(function() { 
        _updateSetting(scope, e); 
        }); 
       }); 
      }, 

      template : "<input type='hidden' class='timezoneSelector' style='width: 100%;'>" 
     } 
    }); 
+0

''적용 범위에주의하십시오. $ apply (fn)'''- http://jimhoskins.com/2012/12/17/angularjs-and-apply.html - * $ apply는 코드를 실행할뿐만 아니라 try/catch에서 실행하여 오류가 항상 잡히고 $ digest 호출은 finally 절에 있습니다. 즉, throw되는 오류와 상관없이 실행됩니다. 그건 꽤 좋은거야. * –

+0

범위를 가지고 있는지 확인하고 싶다. $ apply는 범위를 업데이트 할 때 좋은 캐치이다. –

1

잘 모르겠어요 알려 주시기 이 일의 방법은, 그러나 당신이 관심이 무엇을 위해 일해야

app.directive('timezone', function(timezones) { 
    var _updateSetting = function(locations) { 
     console.log(locations); 

    }; 

    return { 
     restrict: 'E', 

     link: function(scope, el, attrs) { 
      el.select2({ data: timezones.get() }).on("change", function() { 
       _updateSetting(scope.locations); 
      }); 
     }, 

     template : "<input type='hidden' class='timezoneSelector' style='width: 100%;'>" 
    } 
}); 
+0

물론. 나는 범위에 접근하기가 쉽다. 위의 이벤트 핸들러를 정의했다는 사실이다. –