gpt4 book ai didi

javascript - 如何在 angularjs 中单独将指令附加到 div

转载 作者:行者123 更新时间:2023-12-03 08:43:21 25 4
gpt4 key购买 nike

HTML:

<div ng-app = "myApp" ng-controller = "someController as Ctrl">

<div class = "clickme" ng-repeat = "elems in Ctrl.elem" ng-click ="click()">
{{elems.title}}
click me
<div id="container">
</div>
</div>

Angularjs

var Elems = [{title : "1"},
{title : "2"},
{title : "3"}];

var myApp = angular.module('myApp', []);
myApp.controller('someController', function($scope) {
var self = this;
self.elem = Elems;
$scope.click = function(){
//append directive <test-Input></test-Input>
};

});

myApp.directive('testInput',function(){
return {
restrict: 'E',
replace: false,
transclude: false,
template: '<div>asdasdasdasd</div>',
controller: function($scope) {

}
};
});

点击时如何将指令附加到单个 div 上?我知道使用 Jquery 会很容易,但以 Angular 方式很难做到。

最佳答案

您不想这样做,Angulars 的优点之一是您不必自己处理更改 HTML,而是使用数据绑定(bind)和模板,建立 MVC 模式。你还在用 jQuery 思考;-)

仅更改点击时的数据,并使用 ng-repeat 为您添加 Angular 模板。

P.S.:为什么在 Controller 中使用 $scope ?您使用 controller 作为-sntax(这很好),您可以简单地将 click()-funciton 绑定(bind)到 Controller 而不是 $scope

关于javascript - 如何在 angularjs 中单独将指令附加到 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32991657/

25 4 0
文章推荐: javascript -