Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Two-Way Data-Binding in AngularJS

I'm new to AngularJS. A long time I tried to abuse it the way I've always used Javascript-Frameworks like JQuery or Mootools. Now I understood that it's not gonna work like that anymore... But I've come across some big problems since I always generate my HTML-output with a CMS.

So it's pretty static, when it first comes out... Small example:

<ul>
 <li>foo <span>delete</span></li>
 <li>bar <span>delete</span></li>
 <li>blub <span>delete</span></li>
</ul>

Now I thought, that Two-Way Databinding means I can generate the View with help of the Angular Scope and Controller, but also can generate Models by the View.

I may got something confused there... So here's my question. Is there any way to initiate Models from static HTML-output from a CMS?

I tried something like this...

<ul ng-controller="Ctrl">
 <li ng-init="item[0].name=foo">{{item[0].name}} <span ng-click="remove(0)">delete</span></li>
 <li ng-init="item[1].name=bar">{{item[1].name}} <span ng-click="remove(1)">delete</span></li>
 <li ng-init="item[2].name=blub">{{item[2].name}} <span ng-click="remove(2)">delete</span></li>
</ul>

And in my controller I wrote a delete function. But when it did delete, it did only delete the name... the span-button was still there

It did work though when I defined my data as an javascript-array and did the whole output via Angular with ng-repeat... like this:

<ul ng-repeat="it in item">
 <li>{{it.name}} <span ng-click="remove($index)">delete</span></li>
</ul>

I hope I made a point here and everyone get's my dificulty and problems? Can anyone tell me if what I was trying there is possible at all?

like image 370
Preexo Avatar asked Jan 16 '23 03:01

Preexo


1 Answers

This is a common issue people have adjusting to Angular and other frameworks like it.

You don't need your server to render the HTML for you anymore. All you need to do is set up the template, and load the proper data into the scope.

<ul ng-controller="Ctrl" ng-init="getMyItems()">
 <li ng-repeat="item in items">{{item.name}} <a ng-click="remove($index)">delete</a></li>
</ul>

And in your controller you'd do something like this

app.controller('Ctrl', function($scope, $http) {
   $scope.items = [];
   $scope.getMyItems = function(){
       $http.get('/my/json/stuff/url').success(function(data) {
           $scope.items = data;
           $scope.$apply();
       });
   };
});

Now I know you're probably thinking "but I don't want to make a seperate request to get my JSON. And that's fine (probably irrelevant, but fine)... All you need to do is stick it into a global variable and retrieve it with $window instead.

like image 184
Ben Lesh Avatar answered Jan 27 '23 20:01

Ben Lesh