2014-10-26 42 views
2

我的指令包含一個JavaScript對象。我試圖找到與jquery綁定到這個javascript對象的所有html元素。如何使用jquery獲取angularjs對象的綁定數據?從帶有angularjs指令的html元素中提取綁定的angularjs數據

也許上面的代碼更好地解釋了我的計劃。

angular.module('app').directive('highlight', [ 
    '$rootScope', '$compile', function ($rootScope, $compile) { 
     return { 
      replace: true, 
      templateUrl: 'highlight.html', 
      link: function (scope, element, attrs) { 

       //this data object do we need to highlight 
       scope.Tohighlight; 

       $($.find('input, select')).each(function() { 
        //todo extract data if input or selection are binding data 
        //<input type="x" data-ng-model="data" /></span> 
        var data = angular.extractDataFromhtmlelement($(this)); 
        //if html element contains our data add some css stuff 
        if(data == scope.Tohighlight) 
        { 

        } 
       }); 
      }; 
    } 
]); 

我不知道我的目的是否存在angularjs方法。我怎樣才能得到綁定的jQuery對象的angularjs數據模型?謝謝。

+0

我已經更新了我的答案http://stackoverflow.com/a/26578630/947687。對你有幫助嗎? – dizel3d 2014-10-27 08:54:01

回答

1

您可以使用scope()方法和$parse服務來完成。 Example

link: function(scope, element) { 
    var inputElement = element.find('input'); 
    var inputModelGetter = $parse(inputElement.attr('ng-model')); 
    var inputModelSetter = inputModelGetter.assign; 
    function getInputModel() { 
     return inputModelGetter(inputElement.scope()); 
    } 
    function setInputModel(value) { 
     inputModelSetter(inputElement.scope(), value); 
    } 
    // ... 
} 
+0

謝謝。但是對於element.find()。scope()我確實得到了元素的視圖模型而不是綁定對象/屬性。 – Briefkasten 2014-10-27 09:06:21

+0

@Briefkasten,我用$ parse服務更新了我的答案。想想,這是你想要的。 – dizel3d 2014-10-27 09:17:51

+0

感謝你的例子。這正是我需要的。我目前的問題是$ parse(boundExpression);表達式會拋出一個「TypeError:對象不是函數」。當我調試$ parse對象時可用。你有什麼提示嗎?我的修改示例http://jsfiddle.net/dizel3d/h5Ls3dbv/ – Briefkasten 2014-10-27 10:34:06