문제

I'm writing my first directive in angular- it's essentially just a wrapper on the freebase search widget written in jquery.

I want to make the directive application independent (with the only dependencies being external css and jquery).

Here is a plunkr of the directive as it is now.

And the directive itself:

directive('suggest', function() {
  return {
      restrict: 'E',
      template: "<input type='text'>",
      replace:true,
      link: function(scope, element, attrs) {
        var language = 'en'; //set english as default language
        if (attrs.lang){
          language = attrs.lang;
          attrs.$observe('lang', function(value) {
            console.log("lang val " + value);
            language = value;
          });
        }
        $(element).suggest({
          "lang": language
        })
        .bind("fb-select", function(e, data) { 
          console.log(data);
        });
      }
  };
});

When the user selects an item from the dropdown menu, the following function runs:

.bind("fb-select", function(e, data) { 
          console.log(data);
        });

What is the best practice for feeding the data from the selection to the application thats using it?

도움이 되었습니까?

해결책

The most angular way would be to achieve this using data binding (2 way) in an isolated scope:

 restrict: 'E',
      template: "<input type='text'>",
      replace:true,
      scope:{
         myModel:'='
      },
      link: function(scope, element, attrs) {
      ............

and inside that select function:

.bind("fb-select", function(e, data) { 
          console.log(data);
          scope.myModel=data;
});

usage:

<suggest my-model="someModel" .... />

and in your controller $scope:

$scope.someModel="";

You still need to handle the initial binding for that pre-selected model in your directive though, but yea, the cleanest way is 2 way data binding through an isolate scope.

EDIT

These 2 articles are excellent for helping port jquery plugins to angular:

http://rogerz.github.io/blog/2013/09/27/jQuery-to-angularjs/

http://henriquat.re/directives/advanced-directives-combining-angular-with-existing-components-and-jquery/angularAndJquery.html

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top