2013-04-25 232 views
1

我在AngularJS中創建了一個自定義指令。 在鏈接函數中,我將ng-model和ng-options屬性添加到內部模板,但不幸的是綁定不起作用。 但是,當我把內部模板放入我的html文件中時,一切正常。與AngularJS綁定的指令

application.directive("customSelect", function() { 
var directive = { 
    restrict: 'E', 
    template: '<select name="ArrDeplocation" class="arrdepSelect"></select>', 
    link: function (scope, elem, attr) { 
     console.log('scope: ', scope); 
     console.log('element: ', elem); 
     console.log('attribute: ', attr); 

     $(elem.children()[0]).attr('ng-model', 'model.selectedCity'); 
     $(elem.children()[0]).attr('ng-options', 'city for city in model.cities'); 

     $(elem.children()[0]).selectmenu(); 

    } 
}; 
return directive; 
}); 
+1

試過了,它拋出異常,說$ apply正在處理 – Dimkin 2013-04-25 07:32:15

回答

3

我不明白你爲什麼需要在鏈接func中設置屬性。 你可以簡單地把你的模板。

http://plnkr.co/edit/9u6nkLYKHxBBiJ60mpbF?p=preview

app.directive("customSelect", function() { 
    var directive = { 
    restrict: 'E', 
    template: '<select name="ArrDeplocation" class="arrdepSelect"' 
    + 'ng-model="model.selectedCity" ng-options="city for city in model.cities"> </select>', 
    link: function (scope, elem, attr) { 
     // run jquery mobile methods here... 
    } 
    }; 
    return directive; 
}); 

您可能要闡述你真的想在這裏實現什麼。

0

如果你想在連接功能中修改你的模板,那麼你必須重新編譯吧。

解決方案:http://plnkr.co/edit/bpiqXdQe91RJBaJXTPXO?p=preview

app.directive("customSelect", function ($compile) { 
    return { 
    restrict: 'E', 
    template: '<select name="ArrDeplocation" class="arrdepSelect"></select>', 
    link: function (scope, elem, attr) { 
     elem.find('select').attr({ 
     'ng-model': 'model.selectedCity', 
     'ng-options': 'city for city in model.cities' 
     }); 
     var tpl = elem.html(); 
     elem.html($compile(tpl)(scope)); 
     elem.find('select').selectmenu(); 
    } 
    }; 
}); 

$compile("html string")編譯模板分爲:

其用於結合模板(DOM元素/樹)的範圍的鏈接功能