0

I created some value named information and tried to edit it. How ever it is not effect in controller. Then, example in below not working.

(function () {
    var app = angular.module('app', []);

    app.value('information', []);

    app.run(['information', function (information) {
        information = [1, 2, 3, 4];
    }]);

    app.controller('myController', [
    '$scope', 'information', function ($scope, information) {
        $scope.inf = information;
    }]);
})();
<!DOCTYPE html>
<html>
<head>
    <title></title>
	<meta charset="utf-8" />
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
    <script src="app.js"></script>
</head>
<body ng-app="app">
    <div ng-controller="myController">
        <p ng-repeat="i in inf">
            {{ i }}
        </p>
    </div>
</body>
</html>

1
  • 1
    try information.push(1, 2, 3, 4) Commented Sep 10, 2015 at 10:32

2 Answers 2

2

Because when you inject information, it is a reference to the information object which is stored in Angular cache.

I do not recommend to modify the value from the controllers (although you can: JSFiddle).

You'd better use factory:

app.factory('information', function () {
    var info = [];
    return {
        get: function () {
            return info;
        },
        set: function (newInfo) {
            info = newInfo;
        }
    };
});

And inside your controller, use information.get() and information.set() to do the trick.

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

Comments

1

You can use

Angular

(function () {
    var app = angular.module('app', []);

    app.value('information', []);

    app.run(['information', function (information) {
        information.push(1,2,3,4); //use this
    }]);

    app.controller('myController', [
    '$scope', 'information', function ($scope, information) {
        $scope.inf = information;
    }]);
})();

Refer plunker

Comments

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.