简体   繁体   中英

Work with dynamic elements in AngularJS

I tried to make a simple counter with a variable displayed in html and a function to increment it, and it worked. But when i tried to display same variable in javascript in initialization step ( init() ) this contour didn't work anymore, or just don't display correctly. I tried to solve this problem with $compile but didn't worked well. Please tell me where are mistakes?

My html code is:

<body class="max_height" ng-app="myApp">
    <div class="container max_height" ng-controller="myCtrl">
        <div class="col-xs-12 col-sm-8 col-md-6 col-lg-6 col-sm-offset-2 col-md-offset-3 col-lg-offset-3 text-center" id="play" tabindex="0" ng-init="init()">
            {{ contor }}
        </div>
        <button id="increment" ng-click="increment()">Increment</button>
    </div>

    <script src="js/angular.min.js"></script>
    <script src="js/script2.js"></script>
</body>

My javascript code is:

var app = angular.module("myApp", []);

app.controller("myCtrl", function($scope, $compile) {
    $scope.contor = 0;
    $scope.init = function() {
        var element = angular.element(document.querySelector('#play'));
        var generated = element.html('<h3>'+$scope.contor+'</h3>');
        $compile(generated.contents())($scope);
    }
    $scope.increment = function(){
        $scope.contor ++;
    }
});

So my Question is: why when div with id is loaded statically variable for counter is changed automatically and when same div is load in javascript with function init() variable for counter is not changed anymore.

why when div with id is loaded statically variable for counter is changed automatically and when same div is load in javascript with function init() variable for counter is not changed anymore.

Because you doing it wrong.

Here '<h3>'+$scope.contor+'</h3>' you get string '<h3>0</h3>' as you can see this string not depends on any variables.

So, you should change it to

'<h3>{{contor}}</h3>'

and better not use compile service inside controller, and just change html to

<div class="col-xs-12 col-sm-8 col-md-6 col-lg-6 col-sm-offset-2 col-md-offset-3 col-lg-offset-3 text-center" id="play" tabindex="0" ng-init="init()">
    <h3>{{ contor }}</h3>
</div>

in your controller you did not call $scope.init(). That's why this is not work.

Use var generated = element.html('<h3>'+contor+'</h3>');
Instead var generated = element.html('<h3>'+$scope.contor+'</h3>');

I took reference Running AngularJS initialization code when view is loaded

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