简体   繁体   中英

How to create dynamic provider in angularjs

Doesn`t show in page

 $scope.sayHi=function(provider) { $scope.Name=provider.Name console.log(provider) } $http.get("data.php") .success(function(response) { response.records.forEach(function($scope) { app.provider($scope.City , function () { return { $get:function() { return { Name:$scope.Name } } } }) }) }); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.11/angular.min.js"> <input ng-model="city"> <p ng-click='sayHi(city)'>Click </p> <p>This is name: {{name}}</p > Blockquote**strong text** </script> 

Could i make a provider and accessed to it used the ng-model in page

You can add a defined service/provider to your controller by injection.

Define it in your module:

app.provider("myProvider", ['$http', function($http) {
   getXyz: function(callback) {
      $http.get("data.php").success( callback );
   }
}]);

Btw it is not a good idea to start the names of your own functions with a $ sign becaus this is used by angularfor internal variables. There is a chance that name collide.

Then use it in your controller, there is no need to access it on your view.

app.controller( "myController", ['$scope', 'myProvider', function($scope, myProvider){
   $scope.sayHello = function(){     
      myProvider.getXyz(function(response) {
         $scope. ...
      });
   }
}

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