我是angularjs的新手,构建我的第一个角度应用程序现在我想使用自定义指令显示我现在在表格中显示的数据。 谁能告诉我怎么能这样做? 我只想要一个自定义指令,所有数据都应该使用该指令显示。 是自定义指令应该放在一个单独的文件中? 请指导我怎么办?
这是我的控制器:
'use strict';
app.controller('myAppCtrl', function ($scope, $http) {
$scope.names = []
$http.get('https://www.reddit.com/r/worldnews/new.json')
.success(function (response) {
$scope.names = response.data.children;
})
});
答案 0 :(得分:2)
你应该在网上浏览一些资源来研究角度指令。
https://docs.angularjs.org/guide/directive
http://www.tutorialspoint.com/angularjs/angularjs_custom_directives.htm
初学者的简单指令方法 //控制器
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
});
//指令
app.directive('simpleDemo',function(){
var newtemplate = function(){
var template = '<i class="glyphicon glyphicon-remove"><i>';
return template;
}
return {
restrict: 'E',
template: newtemplate
}
})
// HTML
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<button><simple-demo></simple-demo></button>
答案 1 :(得分:0)
它可能对你有帮助!
<html>
<head>
<title>Angular JS Custom Directives</title>
</head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.directive('student', function() {
var directive = {};
directive.restrict = 'E';
directive.template = "Student: <b>{{student.name}}</b> , Roll No: <b>{{student.rollno}}</b>";
directive.scope = {
student : "=name"
}
directive.compile = function(element, attributes) {
element.css("border", "1px solid #cccccc");
var linkFunction = function($scope, element, attributes) {
element.html("Student: <b>"+$scope.student.name +"</b> , Roll No: <b>"+$scope.student.rollno+"</b><br/>");
element.css("background-color", "#ff00ff");
}
return linkFunction;
}
return directive;
});
mainApp.controller('StudentController', function($scope) {
$scope.Mahesh = {};
$scope.Mahesh.name = "Mahesh Parashar";
$scope.Mahesh.rollno = 1;
$scope.Piyush = {};
$scope.Piyush.name = "Piyush Parashar";
$scope.Piyush.rollno = 2;
});
</script>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app="mainApp" ng-controller="StudentController">
<student name="Mahesh"></student><br/>
<student name="Piyush"></student>
</div>
</body>
</html>
参考网址:
https://www.airpair.com/angularjs/posts/creating-components-p3-angular2-directives http://tutorials.jenkov.com/angularjs/custom-directives.html
http://www.sitepoint.com/practical-guide-angularjs-directives/