简体   繁体   中英

How can we use $scope.$apply method in angular like javascript apply method like function.apply(elem)?

I created a page with dynamic content in pure javascript and angular in similar.

I used apply method in javascript to reuse the function assigned to other element. It works perfectly. I am unable to do the same in angular. please see the below plunkers created in JS and Angular. In function move() method, by onclick I animated to move the text to some distance. To see animation Click on all texts in output in both plunkers. In JS plunker To animate the firstChild in onload, in line 38 I used move.apply(firstElem); But I am unable to do the same thing in angular. I want to do something simlpy like I did in JS. Which is the right way to do? can we use $scope.$apply and solve this? or any other way? please help.

functionName.apply(elem); // javascript
$scope.move(elem); // angular

Using JavaScript

Using AngularJS

You're looking at the angular part the wrong way. In normal Javascript/jQuery you generally code in an imperative way, as in you tell an element to "move 100px to the right" or whatever. So in your pure JS example, you tell the element to change its position and color.

In Angular, however, you want to code in a declarative way. In your case, this means that when you have all these text blocks, they should have an attribute to represent whether the element has moved to the right, eg if it should get the styles associated to a moved element.

Instead of modifying the element's style directly, we'll create a css selector to represent a moved element:

.moved {
    left: 100px;
    background: red;
}

We'll then use the ng-class directive to specify when an element should get this class; that is, when it has the moved attribute. We'll also change up the way $scope.move function is used, and remove the ng-init since it's completely unnecessary.

<div ng-class="{moved: x.moved}" ng-click="move(x)" class="divText" ng-repeat="x in myData">
    <div>{{ x.text }}</div>
</div>

Then for the JS part. With the ng-class, basically all the $scope.move function has to do is to give the text object a moved attribute:

$scope.move = function (text) {
    text.moved = true;
};

Then we'll use $timeout to cause the first element to move shortly after the data has been loaded:

  $timeout(function() {
      $scope.move($scope.myData[0])
  }, 500)

And that's it! You now have the same functionality in your Angular example as in your JS one. Here's a plunker link to the edited Angular example.

I'd recommend you to read this excellent stackoverflow answer regarding the differences of coding in jQuery vs Angular: "Thinking in AngularJS" if I have a jQuery background?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM