0

I am new to AngularJS and I am still being a bit confused about calling an custom method of an object and if there is a more lazy way to do it:

https://jsfiddle.net/f4ew9csr/3/

<div ng-app="myApp" ng-controller="myCtrl as myCtrl">
    <h1 ng-click="myCtrl.display()">Click me!</h1>
    <h2>{{ myCtrl.myValue }}</h2>
</div>

var app = angular.module('myApp', []);
app.controller('myCtrl', function() {
    var self = this;
    this.myValue = "Hello world!"
    this.display = function() {
        self.myValue = MyObject.display();
    };
});

var MyObject = new function() {

    var i = 0;

    this.display = function() {
        alert("Change h2");
        return "Hey";
    };

    this.update = function() {
        i += 1;
        return i;
    }
};

So when the h1 is clicked the h2 gets changed and an alert pops up. But my question is that I want to call a custom object method with ng-click in a more efficient way than I am doing right know. And how could I run MyObject.update() with setInterval so it constantly changes my h2 header without jquery?

1 Answer 1

1

I'd suggest you to use $interval in your case which will call the function on specified amount of time interval

Markup

<div ng-app="myApp" ng-controller="myCtrl as myCtrl">
     <h1 ng-click="myCtrl.display()">Click me!</h1>
     <h2>{{ myCtrl.myValue +' Count'+ myCtrl.count}}</h2>
</div>

Code

$interval(function () {
    self.count = MyObject.update();
}, 1000)

Working Fiddle

Sign up to request clarification or add additional context in comments.

2 Comments

Thx for your quick answer, so with angularjs I have to outsource some stuff to the app.controller function? in contrast when using jquery where I can handle everything inside my object, like changing some html?
@user3852496 which object you are talking about..could you explain me more..?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.