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

雨燕双飞 提交于 2020-01-06 20:08:45

问题


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


回答1:


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, e.g. 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?



来源:https://stackoverflow.com/questions/42391877/how-can-we-use-scope-apply-method-in-angular-like-javascript-apply-method-like

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!