我只是在学习 angularjs 并且有一些工作可以将 jQuery 与 angularjs 混合使用。我知道这不是正确的方法,但我不知道 Angularjs 的正确方法是什么。
在 HTML 中我有这个标签,它只是一个按钮,用于将 div 标签动态添加到页面上。
<div ng-controller="pgCtrl">
<button id="new-btn" ng-click="newDiv()">Gimme a div!</button>
</div>
在 javascript 中我有这个:
app.controller('pgCtrl', function($scope){
$scope.newDiv = function(){
// Load an element that uses controller anotherCtrl
$('<div class="blah" ng-controller="anotherCtrl">' +
'<button id="another-btn" ng-click="stuff()">-</button>{{stuff}}' +
'</div>').appendTo('body');
angular.bootstrap($('.blah'), ['app']);
};
});
我知道这不是使用 Angularjs 执行此操作的“正确”方法。我正在混合使用各种基本的 jQuery,它可以工作,但我没有学到任何东西。
最佳答案
使用 Angular 总是先考虑更新范围对象(模型)。在标记( View )中,您有许多 ng
内置指令来处理处理范围对象。
事实上,当您开始使用 Angular 时,最好不要在页面中包含 jQuery。它有助于迫使您远离 jQuery DOM 操作方法并开始思考模型/ Controller / View
这篇文章对于任何从 jQuery 迁移到 Angular 的人来说都是必读的:How do I “think in AngularJS” if I have a jQuery background?
您的演示的一个简单的开始是:
app.controller('pgCtrl', function($scope){
$scope.items=[];
$scope.newDiv=function(){
$scope.items.push( {stuff: 'Some stuff text'}
}
})
然后在 View 中将使用 ng-repeat
这样您就可以根据需要多次点击按钮并继续添加 stuff
<div ng-repeat="item in items" >
<div class="blah" ng-controller="anotherCtrl">
<button id="another-btn" ng-click="stuff()">-</button>{{item.stuff}}
</div>
</div>
关于javascript - 如何使用带 Angular 动态 Controller 附加 div 标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19748440/