2016-01-04 50 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); 
    } 
    })