2017-11-24 3 views
1

Ich bin neu in AngularJS. Ich mache ein Projekt, bei dem der Markenname aus einer Datenbank kommt. Ich muss Label-ID als Parameter übergeben und Label-Name abrufen. Wenn die Seite geladen wird, wird der Wert im Label initialisiert. Aber das Problem ist der Wert setzt, wenn ich ng-click verwende. Aber ich möchte dies mit ng-init/ng-bind, weil das Klicken auf das Etikett keine Lösung ist.AngularJS-Pass-Label-ID als Parameter in ng-init

Hier ist der Code

<!DOCTYPE html> 
<html> 
<head> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> 
<script> 
var app = angular.module('myApp', []); 
app.controller('myCtrl', function($scope) { 
    $scope.test = function(e){ 
    $scope.label=e.target.id; 
    } 
    }); 
</script> 
</head> 
<body> 
<div ng-app="myApp" ng-controller="myCtrl"> 
<label id="lblID" style="border:10px solid red;" ng-click="test($event)">{{label}}</label> 
</div> 
</body> 
</html> 

Antwort

0

Sie sollten, wie unten in eine Richtlinie DOM-Manipulation behandeln.

DEMO

var app = angular.module('myApp', []); 
 
    
 
    
 
app.controller('Ctrl', function ($scope) { 
 
    $scope.doSomething = function (e) { 
 
     alert(e); 
 
    }; 
 
}); 
 

 
app.directive('myDir', function() { 
 
    return function (scope, element, attrs) { 
 
     scope.doSomething(element); 
 
    }; 
 
});
<!DOCTYPE html> 
 
<html> 
 
<head> 
 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> 
 
<script> 
 
var app = angular.module('myApp', []); 
 
app.controller('myCtrl', function($scope) { 
 
    $scope.test = function(e){ 
 
    $scope.label=e.target.id; 
 
    } 
 
    }); 
 
</script> 
 
</head> 
 
<body> 
 
<div ng-app="myApp" ng-controller="Ctrl"> 
 
<label my-dir id="lblID" style="border:10px solid red;" ng-init="test('lblID')">{{label}}</label> 
 
</div> 
 
</body> 
 
</html>

+1

Dank @Sajeetharan. Das funktioniert für mich. Ihr Jungs seid toll. Mein Konzept wächst langsam in angularjs mit der Hilfe von Ihnen wie Sie. Danke noch einmal. –