AngularJS-Pass标签id作为ng-init中的参数

时间:2017-11-24 17:12:24

标签: html angularjs

我是AngularJS的新手。我正在做一个标签名称来自数据库的项目。我必须将标签ID 作为参数传递并检索标签名称。当页面加载时,该值将在标签中初始化。但问题是我使用ng-click时的值集。但我希望使用ng-init / ng-bind,因为点击标签不是解决方案。

以下是代码

<!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>

1 个答案:

答案 0 :(得分:0)

您应该在指令中处理DOM操作,如下所示。

<强>样本

&#13;
&#13;
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);
    };
});
&#13;
<!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>
&#13;
&#13;
&#13;