2016-01-04 53 views
1

我想動態地僅將javascript變量傳遞給角函數。是否有可能,我能不能通過範圍變量在我scenarios.Please也看到了代碼JS提琴動態將javascript變量傳遞給angularJS函數

http://jsfiddle.net/rahulrathore1986/udmcv/293/

<div style="border:solid;color:red;Margin-bottom:4px;"> want to pass 
    only javascript variable to angular function. IS it possible to pass 
JS variable as i can not pass scope variable in my scenarios <ul 
id="ulTabList" > 

</ul> </div> <div style="margin-top:10px;"> <input type="button" 
ng-click="Addli()" value="Create"/> </div> 

的角碼是如下

var app = angular.module('my-app', [], function() { 

}) 

app.controller('AppController', function ($scope, $compile) { 
var workGroupTab ="TestA" 
$scope.Addli =function(){ 
    var el = angular.element('<li ng-click="OpenWorkGroupTab(workGroupTab);" ng-model="workGroupTab">Text of Li</li>' 
    +'<input id="btnClose_4341" type="button" ng-model="workGroupTab" value="btn" style="margin-left:1px;" ng-click="fn_btnClose(workGroupTab)">'); 

    $compile(el)($scope); 
    $("#ulTabList").append(el) 
    } 
    $scope.fn_btnClose = function(v){ 
     console.log('closed button is'+ v); 
    } 

    $scope.OpenWorkGroupTab =function(workgroup){ 
    console.log('workgroup : ' + workgroup); 
    } 
}) 
+0

「我能不能通過範圍變量在我的場景」 - 爲什麼你不能使用範圍是什麼? – Pogrindis

+1

您應該避免在控制器中使用任何DOM操作/ jQuery。如果需要,可以在指令中進行,但在這種情況下更好的方法是使用一組對象並使用'ng-repeat'來構建您的'li'元素列表。那麼你不需要'$ compile',你可以更好地分離關注點(它屬於哪個表示)。 – tylerwal

回答

1

我的理解是,您希望變量workGroupTab在中正確呈現。

您可以執行以下操作來實現這一點:

// assign to a variable so the layout is correct 
var workGroup = "OpenWorkGroupTab('"+ workGroupTab +"');"; 
// then add it within the ng-click element 
var el = angular.element('<li ng-click="'+ workGroup +'" ng-model="workGroupTab">Text of Li</li>' 
+'<input id="btnClose_4341" type="button" ng-model="workGroupTab" value="btn" style="margin-left:1px;" ng-click="fn_btnClose(workGroupTab)">'); 

JsFiddle

0

您正在從jQuery的方法,而不是角的MVC方法,這更多。

而不是在您的javascirpt文件中指定模板,利用ng-repeat自動動態呈現每個li項目。

http://jsfiddle.net/rahulrathore1986/udmcv/293/

HTML

<div style="border:solid;color:red;Margin-bottom:4px;"> 
    want to pass only javascript variable to angular function. IS it passible as i can not pass scope variable in my scenarios 
    <ul id="ulTabList"> 
    <li ng-repeat='item in list' ng-click="OpenWorkGroupTab(item);">Text of Li</li> 
    <input type="button" ng-model="item" value="btn" style="margin-left:1px;" ng-click="fn_btnClose(item)"> 
    </ul> 
</div> 
<div style="margin-top:10px;"> 
    <input type="button" ng-click="Addli()" value="Create" /> 
</div> 

JAVASCRIPT:

angular 
    .module('my-app', []) 
    .controller('AppController', function() { 
    var workGroupTab = "TestA" 
    $scope.list = []; 
    $scope.Addli = function() { 
     $scope.list.push({}); 
    } 
    $scope.fn_btnClose = function(v) { 
     console.log('closed button is' + v); 
    } 

    $scope.OpenWorkGroupTab = function(workgroup) { 
     console.log('workgroup : ' + workgroup); 
    } 
    })