我只是在学习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时,请始终先考虑更新范围对象(Model)。在标记(视图)中,您可以使用许多ng
内置指令来处理处理范围对象。
实际上,当您从angular开始时,最好甚至不要在页面中包含jQuery。它有助于迫使您远离jQuery DOM操作方法,并开始思考Model / Controller / View
这篇文章是从jQuery迁移到angular的任何人必读的文章:如果我有jQuery背景,如何“思考AngularJS”?
您的演示的一个简单启动器将是:
app.controller('pgCtrl', function($scope){
$scope.items=[];
$scope.newDiv=function(){
$scope.items.push( {stuff: 'Some stuff text'}
}
})
然后在视图中将使用,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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句